[hackerrank] Occupations

yenpkr·2025년 4월 23일
0

sql

목록 보기
84/91

문제

정답

with a as (select name,occupation,
           row_number() over(partition by occupation order by name) rn
           from occupations)
select 
    max(case when occupation = 'doctor' then name end) as doctor,
    max(case when occupation = 'professor' then name end) as professor,
    max(case when occupation = 'singer' then name end) as singer,
    max(case when occupation = 'actor' then name end) as actor
from a
group by rn

pivot table

행에 있던 값을 열로 바꾸는 방식

  1. CTE 테이블에서 row_number() 윈도우 함수를 이용해 occupation(직업)끼리 이름을 알파벳 오름차순으로 순번을 매긴 컬럼을 생성한다.
  2. group by rn 으로 같은 순번끼리 (rn=1끼리, rn=2끼리…) 그룹을 묶는다.
  3. rn 별로 case when 으로 occupation 별 name을 가져온다. max를 이용하는 이유는 group by 쓰면, SELECT에 나오는 컬럼들은 반드시 다음 중 하나여야 하기 때문:
    1. GROUP BY에 포함된 컬럼 (rn)
    2. 집계 함수(aggregate function)로 감싼 것 (예: MAX(), MIN(), COUNT() 등)
      → max() 함수를 쓰면 name을 불러올 수 있다. (min)을 써도 가능

또 다른 답

select 
    max(case when occupation = 'doctor' then name end) as doctor,
    max(case when occupation = 'professor' then name end) as professor,
    max(case when occupation = 'singer' then name end) as singer,
    max(case when occupation = 'actor' then name end) as actor
from (select name,occupation,
      row_number() over(partition by occupation order by name) rn
from occupations) a
group by rn

CTE가 아닌 서브쿼리를 from 절에 사용했다.

0개의 댓글