홍동이의 성장일기

[LeetCode] 1179. Reformat Department Table 본문

Tool/SQL 코딩테스트 풀이

[LeetCode] 1179. Reformat Department Table

홍동2 2023. 8. 12. 20:06

 

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 | +-------------+---------+ (id, month) is

leetcode.com

 

Reformat the table such that there is a department id column and a revenue column for each month.

Return the result table in any order.

The result format is in the following example.

 

 

SELECT id
      , SUM(CASE WHEN month = 'Jan' THEN revenue END) AS Jan_Revenue
      , SUM(CASE WHEN month = 'Feb' THEN revenue END) AS Feb_Revenue
      , SUM(CASE WHEN month = 'Mar' THEN revenue END) AS Mar_Revenue
      , SUM(CASE WHEN month = 'Apr' THEN revenue END) AS Apr_Revenue
      , SUM(CASE WHEN month = 'May' THEN revenue END) AS May_Revenue
      , SUM(CASE WHEN month = 'Jun' THEN revenue END) AS Jun_Revenue
      , SUM(CASE WHEN month = 'Jul' THEN revenue END) AS Jul_Revenue
      , SUM(CASE WHEN month = 'Aug' THEN revenue END) AS Aug_Revenue
      , SUM(CASE WHEN month = 'Sep' THEN revenue END) AS Sep_Revenue
      , SUM(CASE WHEN month = 'Oct' THEN revenue END) AS Oct_Revenue
      , SUM(CASE WHEN month = 'Nov' THEN revenue END) AS Nov_Revenue
      , SUM(CASE WHEN month = 'Dec' THEN revenue END) AS Dec_Revenue
FROM Department
GROUP BY id

* ELSE NULL은 생략가능

 

 

💡 개념정리

 

< CASE함수 >

이번 문제에서는 피벗을 하기 위해 CASE 함수를 사용하였다.

 

CASE

WHEN (조건) THEN (결과값)

ELSE (결과값)

END

 


📍본 내용은 데이터리안 'SQL 데이터 분석 캠프 실전반' 을 수강하며 작성한 내용입니다.

728x90
Comments