Oracle - 如何从子查询中返回平均值?
Posted
技术标签:
【中文标题】Oracle - 如何从子查询中返回平均值?【英文标题】:Oracle - How to return average from a subquery? 【发布时间】:2013-05-22 14:57:56 【问题描述】:我需要选择工资高于按部门分组的平均工资的员工。
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
【问题讨论】:
【参考方案1】:最简单的跨数据库方法是使用 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
【讨论】:
以上是关于Oracle - 如何从子查询中返回平均值?的主要内容,如果未能解决你的问题,请参考以下文章
从子查询中获取表名以在一行中用于 Oracle 中的删除/更新/插入子句