单行子查询返回多行

我需要有关oracle

sql的帮助。问题:我有2个表的员工和部门。我从一个查询中获得了部门的平均薪水,我想用它来查看有多少员工比部门的平均薪水更高。到目前为止,我已经知道了。

此查询返回部门的平均值:

select ROUND(AVG(Salary), 2) Dept_avg_sal

from employee, department

where department.department_id = employee.department_id

group by department_name

我想做的是:

select employee_name,

salary,

d.department_name

from employee e,

department d

where salary > (select ROUND(AVG(Salary), 2) Dept_avg_sal

from employee,

department

where department.department_id = employee.department_id

group by department_name)

我得到的错误是:01427。00000-“单行子查询返回多个行”

我知道同一部门的2名员工比平均收入更高,我认为这是造成此问题的原因。

EMPLOYEE_NAME       - SALARY -                -DEPARTMENT_NAME-      DEPT_AVG_SAL           

-------------------- ---------------------- -------------------- ------------

FISHER - 3000.00 - SALES - 2500.00

JONES - 3000.00 - ACCOUNTING - 2750.00

KING - 5000.00 - EXECUTIVE - 4500.00

**SCOTT - 2500.00 - IT - 2100.00

SMITH - 2900.00 - IT - 2100.00**

WILSON - 3000.00 - RESEARCH - 2633.33

任何帮助将非常感激。

回答:

您的初始查询缺少外部查询上的任何连接条件以及内部查询中的任何关联条件,这些条件会将其限制为仅关注部门的行。另外一般你不想group by

name为想必id是主键。

解决这些问题以修复相关的子查询可以

SELECT e.employee_name,

e.salary,

d.department_name

FROM employee e

JOIN department d

ON d.department_id = e.department_id

WHERE e.salary > (SELECT ROUND(AVG(Salary), 2) Dept_avg_sal

FROM employee e2

WHERE e2.department_id = e.department_id)

但是,您可能会发现放弃标量相关子查询并替换为派生表会更好。

SELECT e.employee_name,

e.salary,

d.department_name

FROM employee e

JOIN department d

ON d.department_id = e.department_id

JOIN (SELECT ROUND(AVG(Salary), 2) Dept_avg_sal,

department_id

FROM employee

GROUP BY department_id) e2

ON e2.department_id = e.department_id

AND e.salary > e2.Dept_avg_sal

对于Oracle,以下内容也应该有效

SELECT employee_name,

salary,

d.department_name

FROM (SELECT employee_name,

salary,

d.department_name,

AVG(Salary) OVER (PARTITION BY e.department_id) AS AvgSalary

FROM employee e

JOIN department d

ON d.department_id = e.department_id)

WHERE salary > AvgSalary

以上是 单行子查询返回多行 的全部内容, 来源链接: utcz.com/qa/416024.html

回到顶部