我有一张表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 |
这篇关于各部门最高工资的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!
截断时的 SQL 触发器SQL trigger on Truncate(截断时的 SQL 触发器)
具有多个可选搜索参数的 sql 搜索查询sql search query with multiple optional search parameters(具有多个可选搜索参数的 sql 搜索查询)
SQL 效率:WHERE IN 子查询 vs. JOIN 然后 GROUPSQL Efficiency: WHERE IN Subquery vs. JOIN then GROUP(SQL 效率:WHERE IN 子查询 vs. JOIN 然后 GROUP)
使用 t-SQL 检索 XML 元素名称Retrieving XML element name using t-SQL(使用 t-SQL 检索 XML 元素名称)
在 SQL 输出中插入双引号Insert double quotes into SQL output(在 SQL 输出中插入双引号)
从 SQL SERVER 中的 CTE 中删除行Delete rows from CTE in SQL SERVER(从 SQL SERVER 中的 CTE 中删除行)