1

我需要选择工资高于按部门分组的平均工资的员工。

SELECT * FROM employees
WHERE salary > (SELECT AVG(salary), department_id FROM employees GROUP BY department_id)

它失败了,因为它返回了我 2 列。

我试过这个查询:

SELECT * FROM employees
HAVING salary > AVG(salary)
GROUP BY (department_id)

现在我收到错误消息:ORA-00979: not a GROUP BY expression

4

1 回答 1

3

最简单的跨数据库方法是使用 JOIN:

SELECT employees.*
FROM employees
JOIN ( SELECT department_id, AVG(salary) avgSalary
       FROM employees
       GROUP BY department_id) departmentSalaries
  ON employees.department_id = departmentSalaries.department_id
  AND employees.salary > departmentSalaries.avgSalary

Oracle 最有效的方法是使用分析函数(又名窗口函数):

SELECT * FROM (
  SELECT e.*, AVG(e.salary) OVER ( PARTITION BY e.department_id ) as avgSalary
  FROM employees e) t
WHERE salary > avgSalary
于 2013-05-27T18:15:51.733 回答