HackerRank 공부 2
https://www.hackerrank.com/challenges/what-type-of-triangle/problem
Type of Triangle | HackerRank
Query a triangle's type based on its side lengths.
www.hackerrank.com
Sample Input

Sample Output
Isosceles
Equilateral
Scalene
Not A Triangle
문제 핵심
1. case when 활용해서 컬럼 생성하기
2. case when 순서를 활용해서 집합 관계로 컬럼 생성하기
내 풀이
SELECT
CASE
WHEN A + B <= C OR B + C <= A OR A + C <= B THEN 'Not A Triangle'
WHEN A = B AND B = C THEN 'Equilateral'
WHEN A = B OR B = C OR A = C THEN 'Isosceles'
ELSE 'Scalene'
END AS Type
FROM TRIANGLES;
알게 된 점
CASE WHEN에서 VALUE끼리 포함관계의 집합이 있다면 가장 작은 집합부터 부여해 나가자
https://www.hackerrank.com/challenges/occupations/problem
Occupations | HackerRank
Pivot the Occupation column so the Name of each person in OCCUPATIONS is displayed underneath their respective Occupation.
www.hackerrank.com
문제 핵심
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.
내 풀이
WITH TEMP
AS
(SELECT Name, Occupation, ROW_NUMBER() OVER(PARTITION BY Occupation ORDER BY Name) AS N
FROM OCCUPATIONS)
SELECT T1.NAME, T2.NAME, T3.NAME, T4.NAME
FROM (SELECT NAME, N
FROM TEMP
WHERE Occupation = 'Doctor'
) AS T1
RIGHT OUTER JOIN
(SELECT NAME, N
FROM TEMP
WHERE Occupation = 'Professor'
) AS T2
on T1.N = T2.N
LEFT OUTER JOIN
(SELECT NAME, N
FROM TEMP
WHERE Occupation = 'Singer'
) AS T3
on T2.N = T3.N
LEFT OUTER JOIN
(SELECT NAME, N
FROM TEMP
WHERE Occupation = 'Actor'
) AS T4
on T2.N = T4.N
;
WITH절로 ROW NUMBER 만든 테이블 생성해 두고, ROW NUMBER 기준으로 테이블 JOIN 하면서 NULL 생성함
OUTER JOIN이 없어서 가장 긴 컬럼 직접 확인해서 JOIN 걸었음
다른 사람 풀이
SELECT min(CASE WHEN Occupation = 'Doctor' THEN Name END) AS 'Doctor',
max(CASE WHEN Occupation = 'Professor' THEN Name END) AS 'Professor',
min(CASE WHEN Occupation = 'Singer' THEN Name END) AS 'Singer',
max(CASE WHEN Occupation = 'Actor' THEN Name END) AS 'Actor'
FROM (
SELECT NAME, OCCUPATION, rank() OVER(PARTITION BY OCCUPATION ORDER BY NAME) AS rank_
FROM OCCUPATIONS
) AS t
GROUP BY rank_
- NULL을 생성하는 방법으로 GROUP BY도 가능함
- MIN, MAX는 하나의 Name을 가져오기 위한 aggregation 함수
- case when에서 컬럼 = 0 then 다른 컬럼 -> 이 구조 가능함