문제에서 요구하는 바에 의하면, 출력값이 다음과 같이 나와야 한다.
ORDER BY Docter DESC, Professor DESC, Singer DESC, Actor DESC
위와 같이 정렬하기 위해서는 직업별 이름 순으로 번호를 매겨 주어야 한다.
그렇기에 서브쿼리에서 row_number() OVER (PARTITION BY Occupation ORDER BY NAME)
를 이용하여 직업별로 번호를 매겨 주고, 순서를 정렬해준다.
SELECT
MIN(CASE WHEN Occupation = 'Doctor' THEN Name END) 'Doctor',
MIN(CASE WHEN Occupation = 'Professor' THEN Name END) 'Professor',
MIN(CASE WHEN Occupation = 'Singer' THEN Name END) 'Singer',
MIN(CASE WHEN Occupation = 'Actor' THEN Name END) 'Actor'
FROM (
SELECT *, row_number() OVER (PARTITION BY Occupation ORDER BY NAME) rn
FROM OCCUPATIONS
) O
GROUP BY rn;
OVER(PARTITION BY 기준)
:PIVOT 함수 이용하기
SELECT Doctor, Professor, Singer, Actor
FROM (
SELECT OCCUPATION, NAME, ROW_NUMBER() OVER(PARTITION BY OCCUPATION ORDER BY NAME) RN
FROM OCCUPATIONS
)
PIVOT(
MIN(NAME) FOR Occupation IN (
'Doctor' AS Doctor,
'Professor' AS Professor,
'Singer' AS Singer,
'Actor' AS Actor
)
)
ORDER BY 1, 2, 3, 4;