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...)로 뽑습니다.
'Computer Science > SQL' 카테고리의 다른 글
SQL | HackerRank 평균 오차 구하기 (Replace) (0) | 2025.06.17 |
---|---|
SQL | HackerRank 이진 트리 노드 유형(Root, Inner, Leaf) 구분하는 쿼리 (0) | 2025.06.16 |
SQL | HackerRank 문자열을 이어붙이기 (CONCAT) (0) | 2025.06.14 |
SQL | HackerRank 정규표현식으로 도시 찾기 – DISTINCT와 REGEXP 활용 (0) | 2025.06.13 |
SQL | HackerRank 가장 짧고 긴 도시 이름 찾기 – 문자열 길이 기반 SQL 정렬과 조건 추출 (1) | 2025.06.12 |