https://www.hackerrank.com/challenges/occupations/problem?isFullScreen=true
Occupations | HackerRank
Pivot the Occupation column so the Name of each person in OCCUPATIONS is displayed underneath their respective Occupation.
www.hackerrank.com
문제
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.
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

Sample Output
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.
풀이
처음에 case when을 쓰면 되겠지 했는데 조금 막혀서 찾아보았더니 이렇게 id를 만들어서 group by로 소팅하는 방식이 있었다.
MySQL Pivot: rotating rows to columns
You have to create a database and some related tables where rows of one table will be converted into the columns like PIVOT() function. Run the following SQL statements to create a database named ‘unidb’ and create three tables named ‘students’,
linuxhint.com
참고해서 작성하면 아래와 같다.
/*
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.
*/
select
min(case when t.occupation = 'Doctor' then t.name end) as Doctor
, min(case when t.occupation = 'Professor' then t.name end) as Professor
, min(case when t.occupation = 'Singer' then t.name end) as Singer
, min(case when t.occupation = 'Actor' then t.name end) as Actor
from
(
select occupation, name
, row_number() over(partition by occupation order by name) as 'index'
from occupations
) t
group by t.index
'Data > HackerRank' 카테고리의 다른 글
HackerRank - The Report (0) | 2022.03.03 |
---|---|
HackerRank - Challenges (0) | 2022.03.02 |
HackerRank - Weather Observation Station 20 (0) | 2022.03.02 |
HackerRank - Binary Tree Nodes (0) | 2022.03.02 |
HackerRank - The PADS (0) | 2022.03.01 |