在GROUP BY中,我们可以引用父查询的列吗?

时间:2012-01-04 04:10:33

标签: sql group-by correlated-subquery

如果是,则下面的第一个查询应该是正确的,但显示错误ORA-00979:不是GROUP BY表达式。 如果没有,第三个查询也应该抛出错误......

 SELECT   POSSIBLE.ENAME, POSSIBLE.DEPTNO, POSSIBLE.SAL
 FROM     EMP POSSIBLE
 WHERE    SAL >
   (SELECT   AVG (SAL)
    FROM     EMP AVERAGE group by possible.deptno having
        POSSIBLE.DEPTNO = AVERAGE.DEPTNO) ;

 SELECT   POSSIBLE.ENAME, POSSIBLE.DEPTno, POSSIBLE.SAL
 FROM     EMP POSSIBLE
 WHERE    SAL >
   (SELECT   AVG (SAL)
    FROM     EMP AVERAGE group by average.deptno having
        POSSIBLE.DEPTno = AVERAGE.DEPTno) ;

 SELECT   POSSIBLE.ENAME, POSSIBLE.DEPTNO, POSSIBLE.SAL
 FROM     EMP POSSIBLE
 WHERE    SAL >
   (SELECT   AVG (SAL)
    FROM     EMP AVERAGE group by possible.deptno) ;

2 个答案:

答案 0 :(得分:3)

您的第一个查询应该使用WHERE,而不是HAVINGHAVING子句用于根据聚合(即非组)值进行过滤,而不是过滤分组中涉及的行。

除此之外,您甚至不需要在第一个查询中进行分组。

SELECT   POSSIBLE.ENAME, POSSIBLE.DEPTNO, POSSIBLE.SAL
 FROM     EMP POSSIBLE
 WHERE    SAL >
   (SELECT   AVG (SAL)
    FROM     EMP AVERAGE WHERE
        POSSIBLE.DEPTNO = AVERAGE.DEPTNO) ;

答案 1 :(得分:1)

SELECT   POSSIBLE.ENAME, POSSIBLE.DEPTNO, POSSIBLE.SAL  FROM     EMP POSSIBLE  WHERE    SAL >    (SELECT   AVG (SAL)
    FROM     EMP AVERAGE group by possible.deptno having
        POSSIBLE.DEPTNO = AVERAGE.DEPTNO) ;

我认为错误 ORA-00979:不是GROUP BY 在内部查询的having子句中引用 AVERAGE.DEPTNO