2013-05-14 39 views
0

沿着每個組最大值我有一個Employee表,其內容如下找出與名字

 
------------------------------------------------------------------- 
Name      Department     Salary 
------------------------------------------------------------------- 
Hemant      PTS       100 
Gunjan      PTS       101 
Amol      ADM       50 
Parthiv      ADM       60 
------------------------------------------------------------------- 

我想寫一個查詢由PTS顯示薪水最高的消費羣的名稱。 換句話說,查詢的輸出應該是Gunjan和Parthiv來自不同部門,並​​在該部門中獲得最高工資。

 
------------------------------------------------------------------- 
Name      Department     Salary 
------------------------------------------------------------------- 
Gunjan      PTS       101 
Parthiv      ADM       60 
------------------------------------------------------------------- 

下面的查詢工作正常

SELECT E.Department,MAX(E.Salary) FROM 
Employee E 
GROUP BY Department; 

但我怎麼能與各部門和Max(工資)沿着選擇的名字嗎?

+0

什麼[RDBMS](http://en.wikipedia.org/ wiki/Relational_database_management_system)您正在使用? 'RDBMS'代表*關係數據庫管理系統*。 'RDBMS是SQL'的基礎,並且適用於所有現代數據庫系統,如MS SQL Server,IBM DB2,Oracle,MySQL等等。 – 2013-05-14 06:00:31

回答

4

既然你沒有提到任何RDBMS,這個查詢下面幾乎運行在幾乎所有的RDBMS(但不是所有我想

SELECT a.* 
FROM Employee a 
     INNER JOIN 
     (
      SELECT Department, MAX(Salary) Max_Val 
      FROM Employee 
      GROUP BY Department 
     ) b ON a.Department = b.Department AND 
       a.Salary = b.Max_Val 

輸出

╔═════════╦════════════╦════════╗ 
║ NAME ║ DEPARTMENT ║ SALARY ║ 
╠═════════╬════════════╬════════╣ 
║ Gunjan ║ PTS  ║ 101 ║ 
║ Parthiv ║ ADM  ║  60 ║ 
╚═════════╩════════════╩════════╝