+---------------+---------+ | 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.
The query result format is in the following example:
# Write your MySQL query statement below selectdistinct t.id, (select revenue from Department wheremonth = 'Jan'andid = t.id) as Jan_Revenue, (select revenue from Department wheremonth = 'Feb'andid = t.id) as Feb_Revenue, (select revenue from Department wheremonth = 'Mar'andid = t.id) as Mar_Revenue, (select revenue from Department wheremonth = 'Apr'andid = t.id) as Apr_Revenue, (select revenue from Department wheremonth = 'May'andid = t.id) as May_Revenue, (select revenue from Department wheremonth = 'Jun'andid = t.id) as Jun_Revenue, (select revenue from Department wheremonth = 'Jul'andid = t.id) as Jul_Revenue, (select revenue from Department wheremonth = 'Aug'andid = t.id) as Aug_Revenue, (select revenue from Department wheremonth = 'Sep'andid = t.id) as Sep_Revenue, (select revenue from Department wheremonth = 'Oct'andid = t.id) as Oct_Revenue, (select revenue from Department wheremonth = 'Nov'andid = t.id) as Nov_Revenue, (select revenue from Department wheremonth = 'Dec'andid = t.id) as Dec_Revenue from Department as t;
2 不使用子查询
可以使用聚合函数SUM和case语句
例如 通过case语句把表做个变换
1 2 3 4 5 6 7 8 9
+------+---------+-------+ | id | revenue | month | +------+---------+-------+ | 1 | 8000 | Jan | | 2 | 9000 | Jan | | 3 | 10000 | Feb | | 1 | 7000 | Feb | | 1 | 6000 | Mar | +------+---------+-------+
变为
1 2 3 4 5 6
id Jan Feb Mar 1 8000 null null 2 9000 null null 3 null 10000 null 1 null 7000 null 1 null null 6000
然后再对id分组求和即可
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
# Write your MySQL query statement below selectid, sum(casemonthwhen'Jan'then revenue elsenullend) as Jan_Revenue, sum(casemonthwhen'Feb'then revenue elsenullend) as Feb_Revenue, sum(casemonthwhen'Mar'then revenue elsenullend) as Mar_Revenue, sum(casemonthwhen'Apr'then revenue elsenullend) as Apr_Revenue, sum(casemonthwhen'May'then revenue elsenullend) as May_Revenue, sum(casemonthwhen'Jun'then revenue elsenullend) as Jun_Revenue, sum(casemonthwhen'Jul'then revenue elsenullend) as Jul_Revenue, sum(casemonthwhen'Aug'then revenue elsenullend) as Aug_Revenue, sum(casemonthwhen'Sep'then revenue elsenullend) as Sep_Revenue, sum(casemonthwhen'Oct'then revenue elsenullend) as Oct_Revenue, sum(casemonthwhen'Nov'then revenue elsenullend) as Nov_Revenue, sum(casemonthwhen'Dec'then revenue elsenullend) as Dec_Revenue from department groupbyidorderbyid;