Department Top Three Salaries

The Employee table holds all employees. Every employee has an Id, and there is also a column for the department Id.

Id Name Salary DepartmentId
1 Joe 70000 1
2 Henry 80000 2
3 Sam 60000 2
4 Max 90000 1
5 Janet 69000 1
6 Randy 85000 1

The Department table holds all departments of the company.

Id Name
1 IT
2 Sales

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.

Department Employee Salary
IT Max 90000
IT Randy 85000
IT Joe 70000
Sales Henry 80000
Sales Sam 60000

描述

找出每个部门里 Salary 前三的人(可以并列)

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
-- 方法一

select
Department.Name as Department, Employee.Name as Employee, Employee.Salary
from
Employee inner join Department on Employee.DepartmentId = Department.Id
where
3 > (
select
count(distinct e.Salary)
from
Employee e
where
e.Salary > Employee.Salary and e.DepartmentId = Employee.DepartmentId
)
order by Employee.DepartmentId, Employee.Salary desc
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
-- 方法二

select
Department.Name as Department, e.Name as Employee, e.Salary
from
Department,
(
select
Employee.Name,
Employee.DepartmentId,
Employee.Salary,
@rank := (
case
when @prevDept <> Employee.DepartmentId then 1
when @prevSalary = Employee.Salary then @rank
else @rank + 1 end
) as rank,
@prevDept := Employee.DepartmentId,
@prevSalary := Employee.Salary
from
Employee, (select @rank := 0, @prevDept := 0, @prevSalary := 0) init
order by Employee.DepartmentId asc, Employee.Salary desc
) e
where Department.Id = e.DepartmentId and e.rank <= 3
order by e.DepartmentId, e.Salary desc