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.
The OCCUPATIONS table is described as follows:
Occupation will only contain one of the following values: Doctor, Professor, Singer or Actor.
Jenny Ashley Meera Jane
Samantha Christeen Priya Julia
NULL Ketty NULL Maria
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.
select doctor,professor,singer,actor
from (select name, occupation, row_number() over(partition by occupation order by name) rn
from occupations) --occupation별로 알파벳 오름차순으로 등수를 매김
pivot (
min(name)
for occupation in ('Doctor' doctor,'Professor' professor,'Singer' singer,'Actor' actor)
)
order by doctor,professor,singer,actor;
https://velog.io/@kada/Oracle-PIVOT-함수-사용
https://yurimyurim.tistory.com/11
두 블로그를 봤다.
PIVOT
을 오라클에서 처음 사용해보았기 때문에, 어떻게 쓰는지 감이 안왔다.
그룹함수를 사용해야 하는 것을 알게되었는데, min(name)
이나 max(name)
을 사용하니 내가 원하는 결과가 아니라 한줄 딱 나왔다.
select name, occupation,
row_number() over(partition by occupation order by name) rn
from occupations
--occupation별로 알파벳 오름차순으로 등수를 매김
이 부분이 가장 중요하다고 생각한다.
이렇게 하면, occupation
별로 등수가 매겨졌기 때문에
그것을 위의 deptno
처럼 사용할 수 있게 되고
각 열의 이름은 occupation이 되며, 안에 들어가는 내용이 min(name)
으로 각각 row_number 대로 들어가게 되는 것이다.