問(wèn)題描述
我有一張表EmpDetails
:
DeptID EmpName Salary
Engg Sam 1000
Engg Smith 2000
HR Denis 1500
HR Danny 3000
IT David 2000
IT John 3000
我需要查詢每個(gè)部門的最高工資.
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
上述查詢是公認(rèn)的答案,但不適用于以下情況.假設(shè)我們必須在下表中找到每個(gè)部門薪水最高的員工.
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 | 員工姓名 | 工資 |
---|---|---|
英語(yǔ) | 山姆 | 1000 |
英語(yǔ) | 史密斯 | 2000 |
英語(yǔ) | 湯姆 | 2000 |
人力資源 | 丹尼斯 | 1500 |
人力資源 | 丹尼 | 3000 |
信息技術(shù) | 大衛(wèi) | 2000 |
信息技術(shù) | 約翰 | 3000 |
請(qǐng)注意,Smith 和 Tom 屬于 Engg 部門,他們的薪水相同,是 Engg 部門中最高的.因此查詢SELECT DeptID, MAX(Salary) FROM EmpDetails GROUP BY DeptID"是將不起作用,因?yàn)?MAX() 返回單個(gè)值.以下查詢將起作用.
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 | 員工姓名 | 工資 |
---|---|---|
英語(yǔ) | 史密斯 | 2000 |
英語(yǔ) | 湯姆 | 2000 |
人力資源 | 丹尼 | 3000 |
信息技術(shù) | 約翰 | 3000 |
這篇關(guān)于各部門最高工資的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!