Prepare > SQL > Advanced Select > Occupations
2023. 6. 14. 20:18ㆍHackerRank-My SQL
https://www.hackerrank.com/challenges/occupations/problem?isFullScreen=true
문제
Pivot the Occupation column in OCCUPATIONS so that each Name is sorted alphabetically and displayed underneath its corresponding Occupation. The output column headers should be Doctor, Professor, Singer, and Actor, respectively.
Note: Print NULL when there are no more names corresponding to an occupation.
=> OCCUPATIONS 테이블을 피펏해 의사, 교수, 가수, 배우 각각이 컬럼명이고 아래에 이름이 나오게 하라. 부족하면 NULL 출력.
코드
SELECT
MIN(CASE WHEN Occupation = 'Doctor' THEN Name END),
MIN(CASE WHEN Occupation = 'Professor' THEN Name END),
MIN(CASE WHEN Occupation = 'Singer' THEN Name END),
MIN(CASE WHEN Occupation = 'Actor' THEN Name END)
FROM (
SELECT *, ROW_NUMBER() OVER (PARTITION BY OCCUPATION ORDER BY NAME) RN
FROM OCCUPATIONS) AS K1
GROUP BY RN
- MIN 없으면 오류
- NULL값을 위해 집계함수를 걸어준다고들 하더라....
노트
SELECT *, ROW_NUMBER() OVER (PARTITION BY OCCUPATION ORDER BY NAME) RN
FROM OCCUPATIONS
Eve Actor 1
Jennifer Actor 2
Ketty Actor 3
Samantha Actor 4
Aamina Doctor 1
Julia Doctor 2
Priya Doctor 3
Ashley Professor 1
Belvet Professor 2
Britney Professor 3
Maria Professor 4
Meera Professor 5
Naomi Professor 6
Priyanka Professor 7
Christeen Singer 1
Jane Singer 2
Jenny Singer 3
Kristeen Singer 4
젤 이해 안되는 문제...ㅋ
참조
https://stackoverflow.com/questions/50990171/mysql-pivot-table-with-string-values
https://velog.io/@beemo/SQL-HackerRank-Occupations
'HackerRank-My SQL' 카테고리의 다른 글
Prepare > SQL > Advanced Select > New Companies (0) | 2023.06.27 |
---|---|
Prepare > SQL > Advanced Join > 15 Days of Learning SQL (0) | 2023.06.19 |
Prepare > SQL > Aggregation > Weather Observation Station 20 (0) | 2023.06.14 |
Prepare > SQL > Alternative Queries > Draw The Triangle 2 (0) | 2023.06.12 |
Prepare > SQL > Alternative Queries > Draw The Triangle 1 (0) | 2023.06.11 |