leet code sql 185
185. Department Top Three Salaries
문제
- 각 부서 별 최고 연봉자 top3를 추출
- 연봉이 같다면 둘다 출력 (3명이 넘게 나올 수 있다)
문제 접근
- name은 pk가 아니기 때문에 중복되어서 발생할 가능성이 있어 조심히 다루어야 한다.
- Cte와 dense_rank 함수를 통해 부서 별 연봉 순위를 추출
- 3위 안에 있는 연봉자들만 출력
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
with employee_info as (
select
name,
salary,
departmentId,
dense_rank() over(partition by departmentId order by salary desc) as rn
from Employee
)
select
d.name as Department,
e.name as Employee,
e.salary as Salary
from employee_info e
join Department d
on e.departmentId = d.id
where rn <= 3
order by Department, Salary desc
좋은 방안
- cte 구문 아래에다가 join을 사용하였는데, cte안에서 전부 사용한 뒤 window 함수만 처리하도록 구현
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
with employee_info as (
select
d.name,
e.salary,
e.name as E_name,
dense_rank() over(partition by departmentId order by salary desc) as rn
from Employee e
join Department d
on e.departmentId = d.id
)
select
name as Department,
E_name as Employee,
salary as Salary
from employee_info
where rn <= 3;