Oracle show all employees with greater than average salary of their department(Oracle 显示高于其部门平均工资的所有员工)
问题描述
我正在编写查询以查找收入高于其部门平均工资的员工.我需要显示该部门的员工 ID、工资、部门 ID 和平均工资.
I am writing a query to find employees who earn greater than the average salary within their department. I need to display the employee ID, salary, department id, and average salary of that department.
我有一个几乎可以正常工作的查询,但它一直给我ORA-00904:AVG_SAL":无效标识符"错误.我这样做是否正确.为什么我会收到此无效标识符错误?
I have a query that just almost works but it keeps giving me "ORA-00904: "AVG_SAL": invalid identifier" errors. Am I doing this correctly. Why am i getting this invalid identifier error?
SELECT employee_id, salary, department_id,
(SELECT ROUND(AVG(salary),2)
FROM employees e_inner
WHERE e_inner.department_id = e.department_id) AS avg_sal
FROM employees e
WHERE salary > avg_sal
ORDER BY avg_sal DESC
推荐答案
我不相信您可以在 WHERE 子句中引用列别名(在本例中为 avg_sal).
I don't believe you can refer to a column alias (avg_sal in this case) in a WHERE clause.
您需要重复该内部查询,即:
You'll need to repeat that inner query, i.e.:
SELECT employee_id, salary, department_id,
(SELECT ROUND(AVG(salary),2)
FROM employees e_inner
WHERE e_inner.department_id = e.department_id) AS avg_sal
FROM employees e
WHERE salary >
(SELECT ROUND(AVG(salary),2)
FROM employees e_inner
WHERE e_inner.department_id = e.department_id)
ORDER BY avg_sal DESC
这两个内部查询不是很好,但这是纠正错误的最直接的方法.
Not great, with those two inner queries, but that's the most-straightforward way to correct the error.
更新:尚未对此进行测试,但请尝试以下操作:
Update: Haven't tested this, but try the following:
SELECT e.employee_id, e.salary, e.department_id, b.avg_sal
FROM employees e
INNER JOIN
(SELECT department_id, ROUND(AVG(salary),2) AS avg_sal
FROM employees
GROUP BY department_id) e_avg ON e.department_id = e_avg.department_id AND e.salary > e_avg.avg_sal
ORDER BY e_avg.avg_sal DESC
这篇关于Oracle 显示高于其部门平均工资的所有员工的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Oracle 显示高于其部门平均工资的所有员工
基础教程推荐
- 如何在 CakePHP 3 中实现 INSERT ON DUPLICATE KEY UPDATE aka upsert? 2021-01-01
- 从字符串 TSQL 中获取数字 2021-01-01
- while 在触发器内循环以遍历 sql 中表的所有列 2022-01-01
- 带更新的 sqlite CTE 2022-01-01
- 使用 VBS 和注册表来确定安装了哪个版本和 32 位 2021-01-01
- ORA-01830:日期格式图片在转换整个输入字符串之前结束/选择日期查询的总和 2021-01-01
- 带有WHERE子句的LAG()函数 2022-01-01
- MySQL根据从其他列分组的值,对两列之间的值进行求和 2022-01-01
- MySQL 5.7参照时间戳生成日期列 2022-01-01
- CHECKSUM 和 CHECKSUM_AGG:算法是什么? 2021-01-01
