## Algorithm

Problem Name: Sql - Occupations

In this HackerRank Functions in SQL problem solution,

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.

## Code Examples

### #1 Code Example with MySQL

```Code - MySQL```

``````
SET @d=0, @a=0, @p=0, @s=0;
SELECT MIN(Doctor),MIN(Professor),MIN(SINGER),MIN(Actor)
FROM
(SELECT IF(OCCUPATION='Actor',NAME,NULL) AS Actor,
IF(OCCUPATION='Doctor',NAME,NULL) AS Doctor,
IF(OCCUPATION='Professor',NAME,NULL) AS Professor,
IF(OCCUPATION='Singer',NAME,NULL) AS SINGER,
CASE OCCUPATION
WHEN 'Actor' THEN @a:=@a+1
WHEN 'Doctor' THEN @d:=@d+1
WHEN 'Professor' THEN @p:=@p+1
WHEN 'Singer' THEN @s:=@s+1
END
AS idn FROM OCCUPATIONS ORDER BY NAME )
AS temp GROUP BY temp.idn;
``````
Copy The Code &