ror_coding

[HackerRank] Occupations 본문

Coding Test/SQL

[HackerRank] Occupations

ro_rdil_31 2025. 4. 5. 17:30
728x90

MySQL에서 Pivot 추출하는 방법! CASE-WHEN 을 사용한다.

 

Question

 

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 Output

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

 

Point
  1. ROW_NUMBER()를 이용하여 occupation 열끼리 그룹핑하여 알파벳 순으로 숫자 부여.
  2. GROUP BY 를 rn 으로 해주면 한 행에 value를 나열할 수 있음.
  3. SELECT 절에서 rn = 1인 (각 그룹의 첫 번째) 사람 이름을 출력. 이때 MIN() 혹은 MAX()를 사용해 한 행에 한 값만 나올 수 있게 한다. (이후 rn = 2, 3,... + 특정 열에 값이 더이상 없다면 그 열의 value는 NULL이 들어간다.)

 

Code

 

SELECT
    MIN(CASE WHEN occupation = 'Doctor' THEN name ELSE NULL END) AS 'Doctor',
    MIN(CASE WHEN occupation = 'Professor' THEN name ELSE NULL END) AS 'Professor',
    MIN(CASE WHEN occupation = 'Singer' THEN name ELSE NULL END) AS 'Singer',
    MIN(CASE WHEN occupation = 'Actor' THEN name ELSE NULL END) AS 'Actor'
FROM (SELECT *, ROW_NUMBER() OVER(PARTITION BY Occupation ORDER BY name) AS 'rn'
        FROM OCCUPATIONS) S
GROUP BY rn

 

now me

On my github

 

728x90