hdonghun / SQL

1 stars 0 forks source link

SQL 문제 풀기_ HACKER RANK - Occupations #36

Open hdonghun opened 2 years ago

hdonghun commented 2 years ago

HACKER RANK - Occupations 출처 : https://www.hackerrank.com/challenges/occupations/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: image

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

Sample Input : image

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.

hdonghun commented 2 years ago

MySQL 답안 : SELECT MIN(CASE WHEN OCCUPATION = 'DOCTOR' THEN NAME ELSE NULL END) DOCTOR, MIN(CASE WHEN OCCUPATION = 'PROFESSOR' THEN NAME ELSE NULL END) PROFESSOR, MIN(CASE WHEN OCCUPATION = 'SINGER' THEN NAME ELSE NULL END) SINGER, MIN(CASE WHEN OCCUPATION = 'ACTOR' THEN NAME ELSE NULL END) ACTOR FROM( SELECT OCCUPATION, NAME, ROW_NUMBER() OVER(PARTITION BY OCCUPATION ORDER BY NAME) RN FROM OCCUPATIONS ) T GROUP BY RN ORDER BY RN