选择子查询期间ORA-00937错误

Red*_*ven 0 oracle ora-00937

我正在尝试编写一个查询,该查询返回员工人数,平均工资以及低于平均水平的员工人数.

我到目前为止的查询是:

select trunc(avg(salary)) "Average Pay", 
count(salary) "Total Employees",
(
   select count(salary)
   from employees 
   where salary < (select avg(salary) from employees)
) UnderPaid
from employees;
Run Code Online (Sandbox Code Playgroud)

但是当我运行它时,我在子查询中得到ora-00937错误.

我原以为"计数"函数可能是导致问题的原因,但即使运行更简单的子查询,例如:

select trunc(avg(salary)) "Average Pay", 
count(salary) "Total Employees",
(
  select avg(salary) from employees 
) UnderPaid
from employees;
Run Code Online (Sandbox Code Playgroud)

仍然返回相同的错误.由于AVG和COUNT似乎都是聚合函数,我不确定为什么我会收到错误?

谢谢

nta*_*lbs 5

当您使用scala子查询(它是选择列表中的子查询)时,它应该只返回一行.通常,子查询可以返回多行.因此,当您在具有聚合函数的选择列表中使用它时,您应该使用没有副作用的聚合函数来包装它.

select count(*), (select count(*) from emp) from emp
-- ERROR. Oracle doesn't know that the subquery returns only 1 row.

select count(*), max((select count(*) from emp)) from emp
-- You know that the subquery returns 1 row, applying max() results the same.
Run Code Online (Sandbox Code Playgroud)

或者您可以像这样重写查询:

select avg(salary), count(*), count(case when salary < sal_avg then 1 end)
from (select salary, avg(salary) over () sal_avg from emp);
Run Code Online (Sandbox Code Playgroud)