https://www.hackerrank.com/challenges/occupations/problem?h_r=next-challenge&h_v=zen
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.
[풀이]
GROUP BY 절을 사용하려면 집계 함수를 사용해야하기 때문에 SELECT절에 조회할 데이터를 MIN(Doctor) ... 형식으로 작성한다.
각 OCCUPATION에 따라 NAME을 분류하고, OCCUPATION에 따른 NAME의 수, 즉 해당 직업을 가진 사람 수를 각각 @D, @P, @S, @A에 저장하고 컬럼 이름은 ROWNUMBER이라고 한다.
NAME순으로 해당 값들을 정렬한다.
GROUP BY절에는 ROWNUMBER를 작성하여 같은 행에 존재하는 값들끼리 그룹화 한다.
[코드]
SET @D=0, @P=0, @S=0, @A=0; SELECT MIN(Doctor), MIN(Professor), MIN(Singer), MIN(Actor) FROM ( SELECT CASE WHEN OCCUPATION = "Doctor" THEN NAME END AS Doctor, CASE WHEN OCCUPATION = "Professor" THEN NAME END AS Professor, CASE WHEN OCCUPATION = "Singer" THEN NAME END AS Singer, CASE WHEN OCCUPATION = "Actor" THEN NAME END AS Actor, CASE WHEN OCCUPATION = 'Doctor' THEN (@D:=@D+1) WHEN OCCUPATION = 'Professor' THEN (@P:=@P+1) WHEN OCCUPATION = 'Singer' THEN (@S:=@S+1) WHEN OCCUPATION = 'Actor' THEN (@A:=@A+1) END AS ROWNUMBER FROM OCCUPATIONS ORDER BY NAME ) AS A GROUP BY ROWNUMBER
'SQL > HackerRank' 카테고리의 다른 글
[HackerRank/SQL] New Companies (0) | 2021.11.11 |
---|---|
[HackerRank/SQL] The Report (0) | 2021.11.10 |
[HackerRank/SQL] Binary Tree Nodes (0) | 2021.11.07 |
[HackerRank/SQL] The PADS (0) | 2021.11.06 |
[HackerRank/SQL] Weather Observation Station 19 (0) | 2021.10.31 |