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.connector 禁用查询缓存 2022-01-01
- 无法解决整理冲突 2021-01-01
- 需要 MySQL 5.1 中的抽象触发器来更新审计日志 2021-01-01
- 是否可以执行按位分组功能? 2021-01-01
- SQL:使用来自具有相同列名的两个表中的数据... 2021-01-01
- SQL 效率:WHERE IN 子查询 vs. JOIN 然后 GROUP 2021-01-01
- 在 SQL 中连接多个表 2021-01-01
- SSMS 中的权限问题:“对象 'extended_properties'、数据库 'mssqlsystem_resource'、... 错误 229)上的 SELECT 权限被拒绝" 2022-01-01
- 将 SQL Server DateTime 列迁移到 DateTimeOffset 2021-01-01
- SQL Server 实例在登录协商期间返回无效或不受支持的协议版本 2021-01-01
