홍동이의 성장일기
[LeetCode] 1179. Reformat Department Table 본문
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
'Tool > SQL 코딩테스트 풀이' 카테고리의 다른 글
[LeetCode] 181. Employees Earning More Than Their Managers (0) | 2023.08.12 |
---|---|
[LeetCode] 183. Customers Who Never Order (0) | 2023.08.12 |
[LeetCode] 602. Friend Requests II: Who Has the Most Friends (0) | 2023.04.17 |
[HackerRank] Type of Triangle (0) | 2023.04.17 |
[HackerRank] The PADS (0) | 2023.04.17 |
Comments