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 |
这篇关于各部门最高工资的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:各部门最高工资
基础教程推荐
- 如何在 SQL 中将 Float 转换为 Varchar 2021-01-01
- 什么是 orradiag_<user>文件夹? 2022-01-01
- 如何根据该 XML 中的值更新 SQL 中的 XML 2021-01-01
- 二进制文件到 SQL 数据库 Apache Camel 2021-01-01
- oracle区分大小写的原因? 2021-01-01
- 表 './mysql/proc' 被标记为崩溃,应该修复 2022-01-01
- 在 MySQL 中:如何将表名作为存储过程和/或函数参数传递? 2021-01-01
- MySQL 中的类型:BigInt(20) 与 Int(20) 2021-01-01
- mysql选择动态行值作为列名,另一列作为值 2021-01-01
- 在多列上分布任意行 2021-01-01
