[mySQL] 리트코드 185. Department Top Three Salaries

sehyunny·2023년 5월 24일

mySQL

목록 보기
14/26

https://leetcode.com/problems/department-top-three-salaries/

A company's executives are interested in seeing who earns the most money in each of the company's departments. A high earner in a department is an employee who has a salary in the top three unique salaries for that department.

Write an SQL query to find the employees who are high earners in each of the departments.

Return the result table in any order.


  1. 각 부서별로 월급이 가장 높은 3명을 출력
  2. 정렬 조건 없음
SELECT r.Department,
       r.Employee,
       r.Salary
FROM (
    SELECT Department.name AS Department,
          Employee.name AS Employee,
          Employee.salary AS Salary,
          DENSE_RANK () OVER (PARTITION BY departmentid ORDER BY Salary DESC) AS ranking
    FROM Employee 
        INNER JOIN Department ON Employee.departmentId = Department.id) AS r
WHERE r.ranking <= 3


☑️ point

  • '순위 정하기' 함수의 각 특성을 정확하게 이해하고 있어야 한다

(1) ROW_NUMBER - 중복되는 순위 없음, 동일한 값이더라도 '행의 순서'에 따라 상이한 순위가 매겨짐

(2) RANK - 중복되는 순위 있음, 공동 n등 존재, 단 순위 간 비는 숫자가 발생할 수 있음
ex. 공동2등이 3명일 경우 등수는
1등 - 2등 - 2등 - 2등 - 5등으로, 3등과 4등이 없음

(3) DENSE_RANK - 중복되는 순위 있음, 공동 n등 존재, 순위 간 비는 숫자 없음
ex. 공동2등이 3명일 경우 등수는
1등 - 2등 - 2등 - 2등 - 3등으로 매겨짐

0개의 댓글