Oracle查询数据基于TIME而不显示结果

时间:2017-10-11 01:38:20

标签: oracle

我正在使用Oracle 11g

我想根据TIME ASC对数据进行排序,但我不希望TIME显示结果。

查询

SELECT 
DISTINCT
D.DESCRIPTIONID, 
D.DESCRIPTION,
D.PROFILEID_FK AS PROFILEID_FKS,
Y.PROFILEID_FK AS PROFILEID_FKS2,
Y.TIME
FROM 
WA_BT_TBL_DESCRIPTION D
LEFT OUTER JOIN WA_BT_TBL_DAY Y ON D.DESCRIPTIONID = Y.DESCRIPTIONID_FK
WHERE
D.PROFILEID_FK = 'PF0002' AND
D.ACTIVE = 'Y'
ORDER BY Y.TIME ASC

如果我删除Y.TIME,则会显示错误

ORA-01791: not a SELECTed expression

有什么方法可以按Y.TIME排序,而Y.TIME没有显示结果?

请参阅SQL Fiddle

2 个答案:

答案 0 :(得分:1)

TIME排序而不选择排序的问题是由于您正在进行SELECT DISTINCT查询。在结果集中,D.DESCRIPTIONIDD.DESCRIPTIOND.PROFILEID_FKY.PROFILEID_FK的每种组合只会有一条记录。如果您ORDER BY没有选择它,那么现在的问题是在订购每个潜在的记录时,您希望使用哪个时间值结果集中的单个记录?目前尚不清楚,因此Oracle不会继续进行此类查询。

以下是一个可行的替代查询:

SELECT
    D.DESCRIPTIONID, 
    D.DESCRIPTION,
    D.PROFILEID_FK AS PROFILEID_FKS,
    Y.PROFILEID_FK AS PROFILEID_FKS2
FROM WA_BT_TBL_DESCRIPTION D
LEFT OUTER JOIN WA_BT_TBL_DAY Y
    ON D.DESCRIPTIONID = Y.DESCRIPTIONID_FK
WHERE
    D.PROFILEID_FK = 'PF0002' AND
    D.ACTIVE = 'Y'
GROUP BY
    D.DESCRIPTIONID, 
    D.DESCRIPTION,
    D.PROFILEID_FK,
    Y.PROFILEID_FK
ORDER BY
    MAX(Y.TIME);

这里我已经按查询重写了不同的查询,它在逻辑上与你原来的相同。但现在我ORDER BY 聚合,在这种情况下是最大值。现在,在按时订购时你的意思并不含糊。

请注意,许多RDBMS将使用group by实现一个不同的查询。

答案 1 :(得分:0)

最简单的方法是将Y.TIME埋入子查询中,然后不要在外部查询中删除该字段:

SELECT DESCRIPTIONID, 
       DESCRIPTION,
       PROFILEID_FKS,
       PROFILEID_FKS2
  FROM (SELECT DISTINCT D.DESCRIPTIONID, 
                        D.DESCRIPTION,
                        D.PROFILEID_FK AS PROFILEID_FKS,
                        Y.PROFILEID_FK AS PROFILEID_FKS2,
                        Y.TIME
          FROM WA_BT_TBL_DESCRIPTION D
          LEFT OUTER JOIN WA_BT_TBL_DAY Y
            ON D.DESCRIPTIONID = Y.DESCRIPTIONID_FK
          WHERE D.PROFILEID_FK = 'PF0002' AND
                D.ACTIVE = 'Y'
          ORDER BY Y.TIME ASC)

如果你想成为更好的人,可以将子查询放入公用表表达式:

WITH cteDESC AS (SELECT DISTINCT D.DESCRIPTIONID, 
                                 D.DESCRIPTION,
                                 D.PROFILEID_FK AS PROFILEID_FKS,
                                 Y.PROFILEID_FK AS PROFILEID_FKS2,
                                 Y.TIME
                   FROM WA_BT_TBL_DESCRIPTION D
                   LEFT OUTER JOIN WA_BT_TBL_DAY Y
                     ON D.DESCRIPTIONID = Y.DESCRIPTIONID_FK
                   WHERE D.PROFILEID_FK = 'PF0002' AND
                         D.ACTIVE = 'Y'
                   ORDER BY Y.TIME ASC)
SELECT DESCRIPTIONID, 
       DESCRIPTION,
       PROFILEID_FKS,
       PROFILEID_FKS2
  FROM cteDESC;

祝你好运。