题11:
编写一个SQL查询来重新格式化表,使得新的表中有一个部门id列和一些对应每个月的收入(revenue)列。
解题思路:
(1)group by id 会使department表按照id分组,所有id=1的revenue或者month数据都写在了同一个单元格中,如8000、7000、6000都是写在同一单元格内的。注:这种写法只存在于虚拟表中,帮助我们理解,真正的表是不能这样写的。
(2)case a when b else c end 的句式:case when只会提取当中的第一个数据。当单元格含多个数据的情况,需要使用聚合函数,如sum()或max(),而每个聚合函数的输入就是每一个多数据的单元格。
代码如下:
select id,
sum(case month when Jan then revenue end) as Jan_Revenue,
sum(case month when Feb then revenue end) as Feb_Revenue,
sum(case month when Mar then revenue end) as Mar_Revenue,
sum(case month when Apr then revenue end) as Apr_Revenue,
sum(case month when May then revenue end) as May_Revenue,
sum(case month when Jun then revenue end) as Jun_Revenue,
sum(case month when Jul then revenue end) as Jul_Revenue,
sum(case month when Aug then revenue end) as Aug_Revenue,
sum(case month when Sep then revenue end) as Sep_Revenue,
sum(case month when Oct then revenue end) as Oct_Revenue,
sum(case month when Nov then revenue end) as Nov_Revenue,
sum(case month when Dec then revenue end) as Dec_Revenue
from Department
group by id;