Hacker Rank SQL

Occupations Solution

Hello Friends in this article i am gone to share Hacker Rank SQL Solutions with you | Occupations Solution


Also Visit:ย  The PADS Solution


 

Problem

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:

Column Type
Name String
Occupation String

Occupationย will only contain one of the following values:ย Doctor,ย Professor,ย Singerย orย Actor.

Sample Input

Name Occupation
Samantha Doctor
Julia Actor
Maria Actor
Ashley Professor
Ketty Professor
Christeen Professor
Jane Actor
Jenny Doctor
Priya Singer

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 โ€“ Occupations

MySQL Code
set @r1=0, @r2=0, @r3=0, @r4=0;

select min(Doctor), min(Professor), min(Singer), min(Actor)

from(select case 

when Occupation="Doctor" then (@r1:=@r1+1) 
when Occupation="Professor" then (@r2:=@r2+1) 
when Occupation="Singer" then (@r3:=@r3+1) 
when Occupation="Actor" then (@r4:=@r4+1) end as RowNumber,


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 RowNumber;

 

 

Disclaimer: The above Problems are generated by Hacker Rank but the Solutions are Provided by NYANDER.COM. All Hacker Rank SQL Solutions Shared only for Educational and Learning Purpose.