HackerRank SQL

Occupations

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.

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.

Logic: Use set (user-defined variables) and CASE. Be careful of the order of the occupations

Solution:

set =0, =0, =0, =0;
select min(Doctor), min(Professor), min(Singer), min(Actor)
from(
select case when Occupation = "Doctor" then (:=+1)
when Occupation = "Professor" then (:=+1)
when Occupation = "Singer" then (:=+1)
when Occupation = "Actor" then (:=+1) end as RowLine,
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
)temp
group by RowLine

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store