cs

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

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]

#set을 각 row에 번호를 매기는 것 
SET @D=0, @P=0, @S=0, @A=0;

#순서대로 뽑으려곡 min값으로 하고 
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,
#이건 각 row에 번호를 직업별로 매기는 것
  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 row_number
FROM Occupations
ORDER BY Name)
GROUP BY RowNumber

지금까지 문제중 가장 어려웠다.. 여러 블로그를 뒤져가면서 답을 찾았고, set을 처음 사용해봤다. 

업무하면서 쿼리로 피벗테이블을 만들지는 않아봤기 때문에 더 고생한듯.. 

 

몇번 더 안보고 해보면서 익혀야 할듯 하다. 

set을 통해 row마다 순서를 부여하고 그걸 모두 case when을 사용해서 pivot을 만드는것.. 

'Code Problems > SQL_ HackerRank' 카테고리의 다른 글

[HackerRank] New Company  (0) 2021.11.06
[HackerRank] Binary Tree Nodes  (0) 2021.11.06
[HackerRank] The PADS  (0) 2021.10.04
[HackerRank] Type of Triangle  (0) 2021.10.03
[HackerRank] Employee Salaries  (0) 2021.09.25

+ Recent posts