Skip to main content

LeetCode 185. Department Top Three Salaries SQL Solution

Problem

LeetCode SQL Problem

  1. Department Top Three Salaries

Employee table

idnamesalarydepartmentId
1Joe850001
2Henry800002
3Sam600002
4Max900001
5Janet690001
6Randy850001
7Will700001

Department table

idname
1IT
2Sales

Solution - Dense_Rank() Window Function

Department Top Three Salaries
WITH salary_analysis
AS (
SELECT d.Name AS Department,
e.Name AS Employee,
e.Salary,
dense_rank() OVER (
PARTITION BY d.Id ORDER BY e.Salary DESC
) AS salary_rank_num
FROM Department d
INNER JOIN Employee e ON d.Id = e.DepartmentId
)
SELECT Department,
Employee,
Salary
FROM salary_analysis
WHERE salary_rank_num <= 3
ORDER BY Department,
Salary DESC;

This SQL query uses a common table expression (CTE) named salary_analysis to calculate the rank of each employee's salary within their respective department. The dense_rank() function is used to assign a rank number to each employee's salary, with the highest salary having rank number 1, the second-highest having rank number 2, and so on.

The CTE joins the Department and Employee tables on their respective Id and DepartmentId columns. It selects the Name column from the Department table and the Name and Salary columns from the Employee table, as well as the salary rank number calculated using the dense_rank() function.

The main query selects the Department, Employee, and Salary columns from the salary_analysis CTE, but only for employees whose salary rank number is less than or equal to 3. This filters the results to show only the top three salaries for each department. The results are then sorted by department name and salary in descending order.

Solution - Subquery In Where Clause

Department Top Three Salaries
SELECT D.Name AS Department
,E.Name AS Employee
,E.Salary
FROM Department AS D
INNER JOIN Employee AS E ON D.Id = E.DepartmentId
WHERE (
SELECT COUNT(DISTINCT I.Salary)
FROM Employee AS I
WHERE I.DepartmentId = D.Id
AND I.Salary > E.Salary
) <= 2
ORDER BY D.Name
,E.Salary DESC;

This SQL query retrieves the name of the department, employee, and salary for employees whose salary is not among the top two highest in their department.

The query begins by selecting the Name column from the Department table and the Name and Salary columns from the Employee table, using the INNER JOIN keyword to join the two tables on the Id and DepartmentId columns.

The WHERE clause is used to filter the results. It includes a subquery that selects the count of distinct salaries greater than the salary of the current employee within their department. If this count is less than or equal to 2, the employee is included in the results.

Finally, the results are sorted in ascending order by department name and in descending order by salary.

Query Output

DepartmentEmployeeSalary
ITMax90000
ITJoe85000
ITRandy85000
ITWill70000
SalesHenry80000
SalesSam60000