Hello coders, today we are going to solve Occupations HackerRank Solution in SQL.
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.
Solution – Occupations in SQL
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:[email protected]+1) when Occupation="Professor" then (@r2:[email protected]+1) when Occupation="Singer" then (@r3:[email protected]+1) when Occupation="Actor" then (@r4:[email protected]+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 Problem (Occupations) is generated by Hacker Rank but the Solution is Provided by CodingBroz. This tutorial is only for Educational and Learning Purpose.
3 thoughts on “Occupations in SQL | HackerRank Solution”
The code gives the following error:
DB21034E The command was processed as an SQL statement because it was not a
valid Command Line Processor command. During SQL processing it returned:
SQL0206N “@R1” is not valid in the context where it is used. SQLSTATE=42703
SQL0104N An unexpected token “:=” was found following “n=”Doctor” then (@r1″.
Expected tokens may include: “+”. SQLSTATE=42601
How do I solve this?
Change your DBMS to “MySQL”.
Hope this will help!
This solution is not dynamic but i does not matter how many occupations are available this will work in mssql
with x as (
select occupation, count(*) v from occupations group by occupation
,oc as (
select concat(name ,'(‘,substring(occupation,1,1),’)’) x
,DENSE_RANK() OVER (ORDER BY x asc) AS R
,x2 as (
concat(‘There are a total of ‘, v, ‘ ‘ ,lower(occupation) , ‘s.’) v,
(select max(r) from oc2) +
DENSE_RANK() OVER (ORDER BY v,occupation asc) AS R
select x from
(select x,r from oc2
select v,r from x2) x
order by r