DB(Database)/MySQL

Hackerrank SQL Occupations

ํƒฑ์ ค 2021. 11. 4. 15:17

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 table ์ด์šฉ
-- ๋ฌธ์ž์—ด์—์„œ MIN์€ a๋ถ€ํ„ฐ ์ถ”์ถœ
-- ๋ณ€์ˆ˜ ์„ค์ • set @
-- sub table ์ด๋ฆ„ ์ง€์ •

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) sub
GROUP BY RowNumber;
728x90