본문 바로가기

SQL

(SQL) - LeetCode (easy) 1179. Reformat Department Table

반응형

https://leetcode.com/problems/reformat-department-table/description/

 

Reformat Department Table - LeetCode

Can you solve this real interview question? Reformat Department Table - Table: Department +-------------+---------+ | Column Name | Type | +-------------+---------+ | id | int | | revenue | int | | month | varchar | +-------------+---------+ In SQL,(id, mo

leetcode.com

집계함수와 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;

*더 나은 내용을 위한 지적, 조언은 언제나 환영합니다.