티스토리 뷰

728x90

 

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.

--MS-SQL
SELECT [Doctor],[Professor],[Singer],[Actor]
FROM ( 
    SELECT ROW_NUMBER() OVER(PARTITION BY OCCUPATION ORDER BY NAME) [ROWNUM], * 
    FROM OCCUPATIONS
) A
PIVOT (MAX(NAME) FOR OCCUPATION IN ([Doctor],[Professor],[Singer],[Actor])) AS PVT;

--MySQL
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 @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
        , 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
) AS TEMP
GROUP BY ROWNUMBER;

--MySQL RANK() OVER(PARTITION BY) 사용
SELECT MIN(CASE WHEN Occupation = 'Doctor' THEN NAME END) AS 'Doctor'
    , MIN(CASE WHEN Occupation = 'Professor' THEN NAME END) AS 'Professor'
    , MIN(CASE WHEN Occupation = 'Singer' THEN NAME END) AS 'Singer'
    , MIN(CASE WHEN Occupation = 'Actor' THEN NAME END) AS 'Actor'
FROM (
    SELECT Occupation
        , Name
        , RANK() OVER(PARTITION BY Occupation ORDER BY Name) AS 'row_num'
    FROM OCCUPATIONS 
) A
GROUP BY row_num

11/15일 2차풀이 - 8분

11/17일 3차풀이 - 20분 - RANK() OVER(PATITION BY) 사용

728x90
LIST
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/04   »
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30
글 보관함