혜온의 이것저것

[HackerRank] Occupations (MySQL) 본문

Data Analysis/SQL

[HackerRank] Occupations (MySQL)

혜온 :) 2022. 8. 11. 13:58

https://www.hackerrank.com/challenges/occupations/problem?isFullScreen=true 

 

Occupations | HackerRank

Pivot the Occupation column so the Name of each person in OCCUPATIONS is displayed underneath their respective Occupation.

www.hackerrank.com

 

문제

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.

 

풀이
set @d=0, @p=0, @s=0,@a=0;
select min(doctor), min(professor), min(singer), min(actor)
from (select 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,
		case
		when occupation='Doctor' then (@d:=@d+1)
		when occupation='Professor' then (@p:=@p+1)
		when occupation='Singer' then (@s:=@s+1)
		when occupation='Actor' then (@a:=@a+1)
		end as rowNumber
	from occupations
	order by name) sub
group by rownumber

'Data Analysis > SQL' 카테고리의 다른 글

[HackerRank] New Companies (MySQL)  (0) 2022.08.11
[HackerRank] Binary Tree Nodes (MySQL)  (0) 2022.08.11
[HackerRank] The PADS (MySQL)  (0) 2022.08.10
[HackerRank] Type of Triangle (MySQL)  (0) 2022.08.10
[HackerRank] Employee Salaries (MySQL)  (0) 2022.08.09
Comments