Snoopy [해커랭크/SQL] 34. Occupations(피봇테이블, 윈도우함수)
코딩테스트/해커랭크 SQL

[해커랭크/SQL] 34. Occupations(피봇테이블, 윈도우함수)

Sooyoon Jeong 2023. 3. 14.
 

 

🤔 문제 분석

1. Pivot the Occupation column in OCCUPATIONS so that each Name is sorted alphabetically and displayed underneath its corresponding Occupation.

2. The output column headers should be Doctor, Professor, Singer, and Actor, respectively.

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

 

💡 풀이

SELECT MAX(IF(OCCUPATION = "Doctor", NAME, NULL)) AS DOCTOR,
       MAX(IF(OCCUPATION = "Professor", NAME, NULL)) AS Professor,
       MAX(IF(OCCUPATION = "Singer", NAME, NULL)) AS Singer,
       MAX(IF(OCCUPATION = "Actor", NAME, NULL)) AS Actor
FROM(
    SELECT NAME, OCCUPATION, (ROW_NUMBER() OVER (PARTITION BY OCCUPATION ORDER BY NAME)) AS OCC 
    FROM OCCUPATIONS
    ) AS sub
GROUP BY OCC

댓글