SQL/SQL문풀
[Leetcode:SQL] 부서별로 top3 급여 조회하기
data_2080
2025. 2. 8. 08:47
728x90
출처[Leetcode] : https://leetcode.com/problems/department-top-three-salaries/description/
문제: 부서별 급여 top3의 직원이름과 급여를 조회(동일 급여로 순위 중복이 발생하는 것을 포함)
DENSE_RANK + PARTITION BY
- WITH 절 (top3_salary)
- DENSE_RANK() 윈도우 함수를 사용하여 departmentID별로 급여(salary)가 높은 순서대로 순위 지정
- 같은 급여를 받는 경우 동일한 순위를 부여
- INNER JOIN
- Employee 테이블(s)과 Department 테이블(d)을 departmentID = id 조건으로 조인하여 부서명을 가져오기
- 최종 SELECT
- 부서명(Department), 직원명(Employee), 급여(salary)를 출력
- WHERE s.top3 <= 3 조건을 사용해 각 부서별 급여 상위 3명까지만 필터링
WITH top3_salary AS(
SELECT name
,salary
,departmentID
,DENSE_RANK() OVER(PARTITION BY departmentID ORDER BY salary DESC) AS top3
FROM Employee
)
SELECT d.name AS Department
,s.name AS Employee
,s.salary
FROM top3_salary AS s
INNER JOIN Department AS d
ON s.departmentID = d.id
WHERE s.top3 <= 3
728x90