Occupations

Pivot the Occupation column in OCCUPATIONS so that each Name is sorted alphabetically and displayed underneath its corresponding Occupation. The output should consist of four columns (DoctorProfessorSinger, and Actor) in that specific order, with their respective names listed alphabetically under each column.

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: DoctorProfessorSinger 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 Implementation


Select Doctor, Professor, Singer, Actor from (
    SELECT  name, 
                  occupation,
           ROW_NUMBER() OVER (PARTITION BY occupation ORDER BY name) AS row_number
         FROM OCCUPATIONS
   )dt
   PIVOT (
       MAX(name)
       FOR [Occupation] IN ([Doctor],  [Professor],
                          [Singer],  [Actor])
   )pt
   ORDER BY row_number;
Copied!

Leave a Reply

Your email address will not be published. Required fields are marked *