www.hackerrank.com/challenges/occupations/problem
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.
Answer
# 4개 직업에 행별 숫자를 숫자를 매기기 위한 사전 setting
set @r1 = 0, @r2 = 0, @r3 = 0, @r4 = 0;
with temp as(
select *,
# 직업마다 숫자 매기기
case occupation when 'Doctor' then (@r1 := @r1 + 1)
when 'Professor' then (@r2 := @r2 + 1)
when 'Singer' then (@r3 := @r3 + 1)
when 'Actor' then (@r4 := @r4 + 1)
end as rownum,
# 직업별 칼럼 만들고, 분류시키기
case occupation when 'Doctor' then name end as Doctor,
case occupation when 'Professor' then name end as Professor,
case occupation when 'Singer' then name end as Singer,
case occupation when 'Actor' then name end as Actor
from OCCUPATIONS
order by name # Name is sorted alphabetically
)
# 행 숫자로 group by한 다음 min을 활용하여 출력하기
select min(Doctor), min(Professor), min(Singer), min(Actor)
from temp
group by rownum
Result
'SQL & DB > HackerRank SQL Problem' 카테고리의 다른 글
[HackerRank SQL] New Companies (MySQL) (0) | 2021.02.27 |
---|---|
[HackerRank SQL] Binary Tree Nodes (0) | 2021.02.27 |
[HackerRank SQL] The PADS (MySQL) (0) | 2021.02.27 |
[HackerRank SQL] Type of Triangle (0) | 2021.02.27 |
[HackerRank SQL] Employee Names, Employee Salaries (0) | 2021.02.27 |