HackerRank MySQL - Occupations

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.

  1. SET @r1=0, @r2=0, @r3 =0, @r4=0;
  2. SELECT MIN(Doctor), MIN(Professor), MIN(Singer), MIN(Actor) FROM
  3. (SELECT CASE Occupation WHEN 'Doctor' THEN @r1:=@r1+1
  4. WHEN 'Professor' THEN @r2:=@r2+1
  5. WHEN 'Singer' THEN @r3:=@r3+1
  6. WHEN 'Actor' THEN @r4:=@r4+1 END
  7. AS RowLine,
  8. CASE WHEN Occupation = 'Doctor' THEN Name END AS Doctor,
  9. CASE WHEN Occupation = 'Professor' THEN Name END AS Professor,
  10. CASE WHEN Occupation = 'Singer' THEN Name END AS Singer,
  11. CASE WHEN Occupation = 'Actor' THEN Name END AS Actor
  13. GROUP BY RowLine;
Please click on the like button if it worked

Solution not working or have any suggestions? Please send an email to [email protected]

donate a cup of tea :)

Join Our Facebook Group

Share this solution


Codesadda.com is your home of programming solutions, tutorials, video tutorials and much more. Sign Up for our weekly newsletter to get update about new content.

Like us on Facebook | Connect with us on LinkedIn | Subscribe our Channel on Youtube