各部门最高工资

2021-09-10 00:00:00 sql tsql sql-server

我有一张表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

相关文章