Highest Salary in each department(各部门最高工资)
问题描述
我有一张表EmpDetails
:
DeptID EmpName Salary
Engg Sam 1000
Engg Smith 2000
HR Denis 1500
HR Danny 3000
IT David 2000
IT John 3000
我需要查询每个部门的最高工资.
I need to make a query that find the highest salary for each department.
推荐答案
SELECT DeptID, MAX(Salary) FROM EmpDetails GROUP BY DeptID
SELECT DeptID, MAX(Salary) FROM EmpDetails GROUP BY DeptID
上述查询是公认的答案,但不适用于以下情况.假设我们必须在下表中找到每个部门薪水最高的员工.
The above query is the accepted answer but it will not work for the following scenario. Let's say we have to find the employees with the highest salary in each department for the below table.
部门ID | 员工姓名 | 工资 |
---|---|---|
英语 | 山姆 | 1000 |
英语 | 史密斯 | 2000 |
英语 | 汤姆 | 2000 |
人力资源 | 丹尼斯 | 1500 |
人力资源 | 丹尼 | 3000 |
信息技术 | 大卫 | 2000 |
信息技术 | 约翰 | 3000 |
请注意,Smith 和 Tom 属于 Engg 部门,他们的薪水相同,是 Engg 部门中最高的.因此查询SELECT DeptID, MAX(Salary) FROM EmpDetails GROUP BY DeptID"是将不起作用,因为 MAX() 返回单个值.以下查询将起作用.
Notice that Smith and Tom belong to the Engg department and both have the same salary, which is the highest in the Engg department. Hence the query "SELECT DeptID, MAX(Salary) FROM EmpDetails GROUP BY DeptID" will not work since MAX() returns a single value. The below query will work.
SELECT DeptID、EmpName、Salary FROM EmpDetailsWHERE (DeptID,Salary) IN (SELECT DeptID, MAX(Salary) FROM EmpDetails GROUP BY DeptID)
输出将是
部门ID | 员工姓名 | 工资 |
---|---|---|
英语 | 史密斯 | 2000 |
英语 | 汤姆 | 2000 |
人力资源 | 丹尼 | 3000 |
信息技术 | 约翰 | 3000 |
这篇关于各部门最高工资的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:各部门最高工资


基础教程推荐
- MySQL根据从其他列分组的值,对两列之间的值进行求和 2022-01-01
- MySQL 5.7参照时间戳生成日期列 2022-01-01
- CHECKSUM 和 CHECKSUM_AGG:算法是什么? 2021-01-01
- while 在触发器内循环以遍历 sql 中表的所有列 2022-01-01
- 使用 VBS 和注册表来确定安装了哪个版本和 32 位 2021-01-01
- 从字符串 TSQL 中获取数字 2021-01-01
- ORA-01830:日期格式图片在转换整个输入字符串之前结束/选择日期查询的总和 2021-01-01
- 如何在 CakePHP 3 中实现 INSERT ON DUPLICATE KEY UPDATE aka upsert? 2021-01-01
- 带有WHERE子句的LAG()函数 2022-01-01
- 带更新的 sqlite CTE 2022-01-01