문제
- LeetCode SQL 문제
185. Department Top Three Salaries / Hard
- 문제 내용 : [링크]
내가 작성한 Query
with temp_01 as( select d.name as department , e.name as employee , e.salary as salary , dense_rank() over(partition by d.name order by e.salary desc) as rnum from employee e join department d on e.departmentid = d.id ) select department, employee, salary from temp_01 where rnum<=3
department 부서별 salary
top 3명의 데이터를 출력하는 문제이다.
먼저 사원정보와 부서정보가 모두 필요하므로, JOIN
을 통해 employee
테이블과 department
테이블을 부서id 기준으로 합쳐준다.
이후 department
, employee
, salary
를 출력해준다.
이제 부서별 순위를 구해주어야한다. 순위를 구하는 방법에는 크게 3가지가 있다.
rank()
dense_rank()
row_number()
이 문제의 경우, 동점 순위가 있는 사람도 같이 출력해야하기 때문에, 동점 순위도 같은 순위로 포함할 수 있는 dense_rank()
를 사용하기로 한다.
department
기준(window size), salary
내림차순 순서로 순위를 구해야 하므로 dense_rank() over(partition by d.name order by e.salary desc) as rnum
컬럼을 구해준다.
위에서 구한 테이블을 temp_01
으로 저장해준다.
temp_01
에서 department
, employee
, salary
를 출력하되, WHERE
조건에서 rnum<=3
인 조건을 필터링해준다. (중복을 포함한 top3 데이터만 출력)
⭐ rank()
는 왜 안됨? : 예를 들어, salary
가 300, 200, 200, 100 인 경우, 등수가 1, 2, 2, 4 이런 식으로 출력된다. 이렇게 되면 나중에 WHERE
조건에서 top3의 데이터만 출력할 때, rnum <= 3
(순위) 조건을 주게 되면 salary
가 100인 데이터가 출력되지 않는다. 중복 순위가 몇 개 발생하게 될 지 모르므로, rank()
대신 dense_rank()
를 사용해서 중복 순위가 하나의 순위로 묶일 수 있도록 해준 것이다.