본문 바로가기
SQL

[LeetCode] Department Highest Salary ( sub query, partition by)

by YGSEO 2021. 4. 10.
728x90
# Write your MySQL query statement below
select a.Department, a.Employee, a.Salary
from 
(select D.Name as Department, E.Name as Employee, E.Salary, 
	rank() over (partition by D.Name order by Salary desc) as 'rank'
from Employee  E  join Department D
on E.DepartmentId = D.Id) as a
where a.rank = 1;

 

서브쿼리부터 보자,

from employee 에서

join 으로 employee and deparment을 수행

select 수행

select에서 rank를 사용하는데 여기서 partition by를 사용한다.

group by 처럼 느껴지는데 table을 따로 만든다고 생각하라고 한다.

아무튼, partition by로 Deparment 명 별로 Salary 기준으로 내림차순으로 정렬한 rank를 rank로 column 생성

(rank로 쓰면 동일 순위 같은 순위로)

이렇게 만들어진 table을 a로 만들고

a에 있는 rank가 1인 행들만 선택 후

select에 있는 column 들을 추출

 

서브쿼리에 있는 결과만 출력했을 경우 이러한 형태로 나온다.

Department Employee Salary rank
IT Jim 90000 1
IT Max 90000 1
IT Joe 70000 3
Sales Henry 80000 1
Sales Sam 60000 2

최종 결과물은 여기서 rank = 1인 것들만 추출

 


PARTITION 함수

그룹 내 순위 및 그룹 별 집계를 구할 때 유용하게 사용할 수 있다.



출처: https://ggmouse.tistory.com/119 [초보개발자꽁쥐]

 

728x90

댓글