반응형
https://leetcode.com/problems/reformat-department-table/description/
집계함수와 CASE WHEN 절을 사용해본 문제였습니다.
📕 풀이방법
📔 풀이과정
id와 12월까지의 data를 나열하는데 해당 월에 맞는 data가 있다면 revenue에서 그 값을 select하고 아닌 경우 NULL값을 가져온 다음 두 값의 MAX값을 select해줍니다.
📕 Code
📔 ANSI SQL
SELECT
id,
MAX(CASE WHEN month = 'Jan' THEN revenue ELSE NULL END) AS Jan_Revenue,
MAX(CASE WHEN month = 'Feb' THEN revenue ELSE NULL END) AS Feb_Revenue,
MAX(CASE WHEN month = 'Mar' THEN revenue ELSE NULL END) AS Mar_Revenue,
MAX(CASE WHEN month = 'Apr' THEN revenue ELSE NULL END) AS Apr_Revenue,
MAX(CASE WHEN month = 'May' THEN revenue ELSE NULL END) AS May_Revenue,
MAX(CASE WHEN month = 'Jun' THEN revenue ELSE NULL END) AS Jun_Revenue,
MAX(CASE WHEN month = 'Jul' THEN revenue ELSE NULL END) AS Jul_Revenue,
MAX(CASE WHEN month = 'Aug' THEN revenue ELSE NULL END) AS Aug_Revenue,
MAX(CASE WHEN month = 'Sep' THEN revenue ELSE NULL END) AS Sep_Revenue,
MAX(CASE WHEN month = 'Oct' THEN revenue ELSE NULL END) AS Oct_Revenue,
MAX(CASE WHEN month = 'Nov' THEN revenue ELSE NULL END) AS Nov_Revenue,
MAX(CASE WHEN month = 'Dec' THEN revenue ELSE NULL END) AS Dec_Revenue
FROM Department
GROUP BY id;
*더 나은 내용을 위한 지적, 조언은 언제나 환영합니다.
'SQL' 카테고리의 다른 글
(Tibero 7) - varray 찍먹하기 (0) | 2024.02.05 |
---|---|
(SQL) - LeetCode (easy) 1280. Students and Examinations (0) | 2024.01.12 |
(SQL) - LeetCode (easy) 1084. Sales Analysis III (0) | 2023.10.26 |
(SQL) - LeetCode (easy) 1075. Project Employees I (0) | 2023.10.24 |
(SQL) - LeetCode (easy) 627. Swap Salary (0) | 2023.05.25 |