Skip to main content

LeetCode 184. Department Highest Salary SQL Solution

Problem

LeetCode SQL Problem

  1. Department Highest Salary

Employee table

IdNameSalaryDepartmentId
1Joe700001
2Jim900001
3Henry800002
4Sam600002
5Max900001

Department table

IdName
1IT
2Sales

Solution - Rank() Window Function

Department Highest Salary
-- Rank salary in each department. Highest salary is ranked as 1.
WITH SalaryRankedByDept
AS (
SELECT D.Name AS Department
,E.Name AS Employee
,E.Salary
,rank() OVER (
PARTITION BY D.Id ORDER BY E.Salary DESC
) AS RankNum
FROM Department AS D
INNER JOIN Employee AS E ON D.Id = E.DepartmentId
)
-- Output highest ranked salary in each department
SELECT Department
,Employee
,Salary
FROM SalaryRankedByDept
WHERE RankNum = 1

Query Output

NameNameSalary
SalesHenry80000
ITMax90000
ITJim90000

Solution - Group By

Department Highest Salary
-- Find the highest salary for each department
WITH MaxSalaryByDept
AS (
SELECT DepartmentId
,max(Salary) AS MaxEmpSalary
FROM Employee
GROUP BY DepartmentId
)
-- Select employees who earn the highest salary in his/her department
SELECT D.Name
,E.Name
,E.Salary
FROM Department AS D
INNER JOIN Employee AS E ON D.Id = E.DepartmentId
INNER JOIN MaxSalaryByDept AS MS ON D.Id = MS.DepartmentId
AND E.Salary = MS.MaxEmpSalary

Query Output

NameNameSalary
SalesHenry80000
ITMax90000
ITJim90000