Oracle - 如何从子查询中返回平均值?

时间:2013-05-27 18:12:16

标签: sql oracle group-by

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

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:不是GROUP BY表达式

1 个答案:

答案 0 :(得分: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