ORA-00979: 不是按表达式分组

Pat*_*ick 5 oracle

当我尝试运行此查询时,出现错误:“ORA-00979: not a group by expression”。

select empno, empname
from emp.employee
group by empno, empname
having empmsal > avg(empmsal);
Run Code Online (Sandbox Code Playgroud)

我试图找到工资高于平均水平的员工。你能看出查询有什么问题吗?

对不起,如果这很明显。我是 sql 新手。

小智 3

因为 empno 和 empname 上的 group by 基本上没有意义(假设它们在表中是唯一的),所以更好的方法是:

select empno, empname
from emp.employee
where empmsal > (select avg(empmsal) from emp.employee)
Run Code Online (Sandbox Code Playgroud)

问题是(select avg(empmsal) from emp.employee)它只计算一次 - 出现在 where 条件中,除非您有索引,否则empmsal将执行表扫描,然后再执行主查询。这已经是最好的了。


另一种方法是使用窗口函数:

with cte as
( select empno, empname,
         avg(empmsal) over () as avg_empsal 
  from emp.employee
) 
select empno, empname
from cte
where empmsal > avg_empmsal ;
Run Code Online (Sandbox Code Playgroud)