HackerRank SQL Interview Question: Level Medium
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.
To achieve this output we can create a Pivot query, it aggregates the results and rotate rows into columns and window function Row_Number which is used to assign a sequential integer to each row within a partition of a result set as shown below.
SELECT [Doctor], [Professor], [Singer], [Actor] FROM ( SELECT Occupation, Name, ROW_NUMBER() OVER (PARTITION BY Occupation ORDER BY Name) AS Seq FROM OCCUPATIONS ) AS pvt PIVOT ( MAX(Name) FOR Occupation IN ([Doctor], [Professor], [Singer], [Actor]) ) AS Pvttbl ORDER BY Seq;
You can see, the output of query as shown below.
Lets understand the working of above query.
Pivoting takes a unique values of Occupation column and transformed them into multiple columns of Occupation such as Doctor, Actor, Professor, and Singer in the result set and display an individual Doctor’s name under relevant Occupation column in pivot table.
In this query Row_Number function assign the sequence for each Name values partitioning by Occupation.