본문 바로가기
computer/SQL

[Oracle] 그룹별 상위 3개 데이터 추출 RANK()/DENSE_RANK()

by 몽구스_ 2021. 6. 30.
728x90

 

Oracle

[leetcode] 185. Department Top Three Salaries

 

Employee table:
+----+-------+--------+--------------+
| Id | Name  | Salary | DepartmentId |
+----+-------+--------+--------------+
| 1  | Joe   | 85000  | 1            |
| 2  | Henry | 80000  | 2            |
| 3  | Sam   | 60000  | 2            |
| 4  | Max   | 90000  | 1            |
| 5  | Janet | 69000  | 1            |
| 6  | Randy | 85000  | 1            |
| 7  | Will  | 70000  | 1            |
+----+-------+--------+--------------+

Department table:
+----+-------+
| Id | Name  |
+----+-------+
| 1  | IT    |
| 2  | Sales |
+----+-------+

Result table:
+------------+----------+--------+
| Department | Employee | Salary |
+------------+----------+--------+
| IT         | Max      | 90000  |
| IT         | Joe      | 85000  |
| IT         | Randy    | 85000  |
| IT         | Will     | 70000  |
| Sales      | Henry    | 80000  |
| Sales      | Sam      | 60000  |
+------------+----------+--------+

 

 

rank()함수 사용하기

그룹별 상위 3개 급여 뽑아내기
(겹칠 경우 두개 다 뽑아내기, 그룹별 데이터가 3개미만일 경우 모두 뽑아내기 : ex.2개일 경우 2개만 뽑아내기) 

select d.name department, e.name employee, e.salary
from department d join employee e on d.id = e.departmentid
where e.id in ( select id from (
    select  id, dense_rank() over (partition by departmentid order by salary desc) as rn
                       from employee)where rn <= 3);

 

 

 

Department Top Three Salaries - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

 

댓글