본문 바로가기
Analysis & Visualization/SQL

[SQL] HackerRank - Occupations

by statsbymin 2022. 8. 15.

Pivot the Occupation column in OCCUPATIONS so that each Name is sorted alphabetically and displayed underneath its corresponding Occupation. The output column headers should be Doctor, Professor, Singer, and Actor, respectively.

Note: Print NULL when there are no more names corresponding to an occupation.

Input Format

The OCCUPATIONS table is described as follows:

Occupation will only contain one of the following values: Doctor, Professor, Singer or Actor.

Sample Input

Sample Output

Jenny    Ashley     Meera  Jane
Samantha Christeen  Priya  Julia
NULL     Ketty      NULL   Maria

Explanation

The first column is an alphabetically ordered list of Doctor names.
The second column is an alphabetically ordered list of Professor names.
The third column is an alphabetically ordered list of Singer names.
The fourth column is an alphabetically ordered list of Actor names.
The empty cell data for columns with less than the maximum number of names per occupation (in this case, the Professor and Actor columns) are filled with NULL values.

 

문제요약

OCCUPATIONS 테이블을 Pivot(회전)시키기

피벗된 열의 헤더는 Doctor, Professor, Singer, Actor 순서이고 그 값들을 이름으로 출력 및 정렬한다.

이름이 모두 출력된 열에는 이후 NULL값으로 빈칸을 채워 길이를 맞춘다.

 

풀이

select 
min(case when O.occupation = 'Doctor' then O.name else null end) as Doctor,
min(case when O.occupation = 'Professor' then O.name else null end) as Professor,
min(case when O.occupation = 'Singer' then O.name else null end) as Singer,
min(case when O.occupation = 'Actor' then O.name else null end) as Actor

from (select name, occupation,
    rank() over(partition by occupation order by name) as rnk
    from occupations) O
group by O.rnk;
  1. CASE WHEN문을 통해 각 직업에 맞는 NAME을 출력하거나 NULL값을 출력하도록 하였다.
  2. CASE WHEN문 앞에 min을 적어준 이유는 그룹별 집계함수 GROUP BY로 인해서이다.(line 10)
  3. line 8의 RANK OVER 함수를 통해 OCCUPATION 기준으로 파티셔닝 및 NAME기준 정렬 후 랭크(순위)를 출력한다. 그 결과 OCCUPATION 내에서 이름이 가장 앞서면(A에 가장 가까운 사람) 1, 두 번째 2 순으로 순위가 출력된다.
  4. line 10을 통해 다시 그룹별 출력문을 작성해주면 결과가 도출된다.

 

 

결과