HackerRank SQL: Occupations

Radosław Walczak
2 min readFeb 15, 2024

--

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.

Solution:

with doctorT as
(
select name as doctor,
row_number() over(order by name) as rn
from occupations
where occupation = 'doctor'
),
professorT as
(
select name as professor,
row_number() over(order by name) as rn
from occupations
where occupation = 'professor'
),
singerT as
(
select name as singer,
row_number() over(order by name) as rn
from occupations
where occupation = 'singer'
),
actorT as
(
select name as actor,
row_number() over(order by name) as rn
from occupations
where occupation = 'actor'
)

select doctor, professor, singer, actor
from doctorT
full join professorT on professorT.rn = doctorT.rn
full join singerT on singerT.rn = professorT.rn
full join actorT on actorT.rn = singerT.rn;

--

--