LeetCode 185:Department Top Three Salaries
【Description】
The Employee table holds all employees. Every employee has an Id, and there is also a column for the department Id.
The Department table holds all departments of the company.
Write a SQL query to find employees who earn the top three salaries in each of the department. For the above tables, your SQL query should return the following rows (order of rows does not matter).
Explanation:
In IT department, Max earns the highest salary, both Randy and Joe earn the second highest salary, and Will earns the third highest salary. There are only two employees in the Sales department, Henry earns the highest salary while Sam earns the second highest salary.
【Solution】
Personal solution:
with temp as (
select *,
dense_rank() over (partition by DepartmentId
order by Salary desc) as "rank"
from Employee
)
select d.Name as Department, e.Name as Employee, e.Salary as Salary
from temp as e
join Department as d
on e.DepartmentId= d.Id
where e.rank =1
or e.rank =2
or e.rank =3
Reference solution:
SELECT
d.Name AS 'Department', e1.Name AS 'Employee', e1.Salary
FROM
Employee e1
JOIN
Department d ON e1.DepartmentId = d.Id
WHERE
3 > (SELECT
COUNT(DISTINCT e2.Salary)
FROM
Employee e2
WHERE
e2.Salary > e1.Salary
AND e1.DepartmentId = e2.DepartmentId
)
;