Highest Salary in each department

前端 未结 30 1462
没有蜡笔的小新
没有蜡笔的小新 2021-01-30 22:16

I have a table EmpDetails:

DeptID      EmpName   Salary
Engg        Sam       1000
Engg        Smith     2000
HR          Denis     1500
HR                  


        
30条回答
  •  醉话见心
    2021-01-30 23:18

    Here is a way to get maximum values and names on any version of SQL.

    Test Data:

    CREATE TABLE EmpDetails(DeptID VARCHAR(10), EmpName VARCHAR(10), Salary DECIMAL(8,2))
    INSERT INTO EmpDetails VALUES('Engg','Sam',1000)
    INSERT INTO EmpDetails VALUES('Engg','Smith',2000)
    INSERT INTO EmpDetails VALUES('HR','Denis',1500)
    INSERT INTO EmpDetails VALUES('HR','Danny',3000)
    INSERT INTO EmpDetails VALUES('IT','David',2000)
    INSERT INTO EmpDetails VALUES('IT','John',3000)
    

    Example:

    SELECT ed.DeptID
          ,ed.EmpName
          ,ed.Salary
    FROM (SELECT DeptID, MAX(Salary) MaxSal
          FROM EmpDetails
          GROUP BY DeptID)AS empmaxsal
    INNER JOIN EmpDetails ed
      ON empmaxsal.DeptID = ed.DeptID
     AND empmaxsal.MaxSal = ed.Salary
    

    Not the most elegant, but it works.

提交回复
热议问题