일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | 5 | ||
6 | 7 | 8 | 9 | 10 | 11 | 12 |
13 | 14 | 15 | 16 | 17 | 18 | 19 |
20 | 21 | 22 | 23 | 24 | 25 | 26 |
27 | 28 | 29 | 30 | 31 |
Tags
- 파이썬
- coding
- cte
- lambda
- Stack
- tableau
- 완전탐색
- mysql
- 코테
- sql
- import re
- 프로그래머스
- join
- Growth hacking
- collections
- level4
- 코딩
- 코딩테스트
- time complexity
- coding test
- programmers
- hackerrank
- Level2
- AARRR
- python
- itertools
- Queue
- lv4
- 조합
- counter
Archives
- Today
- Total
ror_coding
[HackerRank] Occupations 본문
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
- ROW_NUMBER()를 이용하여 occupation 열끼리 그룹핑하여 알파벳 순으로 숫자 부여.
- GROUP BY 를 rn 으로 해주면 한 행에 value를 나열할 수 있음.
- 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
'Coding Test > SQL' 카테고리의 다른 글
[HackerRank] Symmetric Pairs (0) | 2025.06.14 |
---|---|
[HackerRank] Binary Tree Nodes (0) | 2025.04.05 |
[Programmers Lv.5] 멸종위기의 대장균 찾기 - 301651 (0) | 2025.01.16 |
[Programmers Lv.5] 상품을 구매한 회원 비율 구하기 - 131534 (0) | 2025.01.16 |
[Programmers Lv.4] 언어별 개발자 분류하기 - 276036 (0) | 2025.01.12 |