SQL 문제풀이

leetcode - 1179. Reformat Department Table

Jerrytwo 2022. 7. 1. 16:16

난이도 : Easy

 

Table: Department

+-------------+---------+
| Column Name | Type    |
+-------------+---------+
| id          | int     |
| revenue     | int     |
| month       | varchar |
+-------------+---------+
(id, month) is the primary key of this table.
The table has information about the revenue of each department per month.
The month has values in ["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"].

 

Write an SQL query to 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.

 

 

if절을 활용한 방법
SELECT id
     , SUM(IF(month = 'Jan', revenue, null)) Jan_Revenue
     , SUM(IF(month = 'Feb', revenue, null)) Feb_Revenue
     , SUM(IF(month = 'Mar', revenue, null)) Mar_Revenue
     , SUM(IF(month = 'Apr', revenue, null)) Apr_Revenue
     , SUM(IF(month = 'May', revenue, null)) May_Revenue
     , SUM(IF(month = 'Jun', revenue, null)) Jun_Revenue
     , SUM(IF(month = 'Jul', revenue, null)) Jul_Revenue
     , SUM(IF(month = 'Aug', revenue, null)) Aug_Revenue
     , SUM(IF(month = 'Sep', revenue, null)) Sep_Revenue
     , SUM(IF(month = 'Oct', revenue, null)) Oct_Revenue
     , SUM(IF(month = 'Nov', revenue, null)) Nov_Revenue
     , SUM(IF(month = 'Dec', revenue, null)) Dec_Revenue
FROM Department
GROUP BY id

Accepted (21.03%)