Computer Science/SQL

SQL | HackerRank MAX(CASE WHEN…)을 활용한 피벗(Pivot) 쿼리

올리브한입 2025. 6. 15. 10:59
반응형

Pivot the Occupation column in OCCUPATIONS so that each Name is sorted alphabetically and displayed underneath its corresponding Occupation. The output should consist of four columns (Doctor, Professor, Singer, and Actor) in that specific order, with their respective names listed alphabetically under each column.

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

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.

MAX(CASE WHEN Occupation = 'Doctor' THEN Name END) AS Doctor

이 구문은 아래와 같은 의미를 가집니다:

  • CASE WHEN 조건문: Occupation 'Doctor'인 경우에만 Name 값을 반환하고, 그 외에는 NULL을 반환합니다.
  • MAX(...) 집계 함수: 여러 행이 있을 경우, NULL을 제외하고 그 중 하나의 값(최댓값)만 선택합니다. 여기서는 각 행마다 하나씩만 있으므로, 해당 조건을 만족하는 Name 하나만 골라낼 수 있게 됩니다.
  • AS Doctor: 결과 열의 이름을 Doctor로 지정합니다.

이와 같은 구문을 직업 수만큼 반복하여, 가로 방향으로 이름을 출력할 수 있습니다.

 

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) AS RowNum
    FROM OCCUPATIONS
) AS SubQuery
GROUP BY RowNum
ORDER BY RowNum;
SELECT Name, Occupation,
       ROW_NUMBER() OVER (PARTITION BY Occupation ORDER BY Name) AS RowNum

이 부분은 직업별로 이름을 알파벳순으로 정렬하고, 각 이름에 번호(RowNum)를 부여합니다. Group by rownum을 사용하여 같은 RowNum을 가진 행끼리 묶은 다음, 각 직업의 이름만 골라서 MAX(CASE WHEN...)로 뽑습니다. 

반응형