[HackerRank] Occupations

MySQL > Occupations


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.


My Answer


-- 1 함수정의
SET @r1=0, @r2=0, @r3=0, @r4=0; 

-- 3 ROWNUM으로 GROUP BY 해주고 최솟값 출력
SELECT MIN(Doctor), MIN(Professor), MIN(Singer), MIN(Actor)
FROM (
-- 2 ROW행 만들기
SELECT CASE WHEN Occupation = 'Doctor' THEN (@r1:=@r1+1)
            WHEN Occupation = 'Professor' THEN (@r2:=@r2+1)
            WHEN Occupation = 'Singer' THEN (@r3:=@r3+1)
            WHEN Occupation = 'Actor' THEN (@r4:=@r4+1) END AS ROWNUM,
       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
FROM OCCUPATIONS
ORDER BY NAME) A
GROUP BY ROWNUM;

2번값만 출력했을때의 결과

최종 출력값

참고
https://haloaround.tistory.com/211

좋은 웹페이지 즐겨찾기