练习sql语句,所有题目来自于力扣(https://leetcode.cn/problemset/database/)的免费数据库练习题。
1179.重新格式化部门表
表:Department
列名 | 类型 |
---|---|
id | int |
revenue | int |
month | varchar |
在 SQL 中,(id, month) 是表的联合主键。这个表格有关于每个部门每月收入的信息。月份(month)可以取下列值 [“Jan”,“Feb”,“Mar”,“Apr”,“May”,“Jun”,“Jul”,“Aug”,“Sep”,“Oct”,“Nov”,“Dec”]。
重新格式化表格,使得 每个月 都有一个部门 id 列和一个收入列。
首先分析表内容,题目只给了一张部门表,记录了每个部门的id,以及每个月的收入。说实话,看到这道题的时候,我觉得肯定需要用到group by,然后写着写着,始终想不出来怎么把这么多月转换成列名,而且表中也没有其他月的数据啊,心想该不会是一个一个月的写吧,我说不至于吧,这么复杂而又简单吗,心里面想肯定有简单的方法,然后最后还是想不出来,看了下题解,好好好,是我想太多,真的是一个一个写出来的。
select id,
case when month = "Jan" then revenue end as Jan_Revenue,
case when month = "Feb" then revenue end as Feb_Revenue,
case when month = "Mar" then revenue end as Mar_Revenue,
case when month = "Apr" then revenue end as Apr_Revenue,
case when month = "May" then revenue end as May_Revenue,
case when month = "Jun" then revenue end as Jun_Revenue,
case when month = "Jul" then revenue end as Jul_Revenue,
case when month = "Aug" then revenue end as Aug_Revenue,
case when month = "Sep" then revenue end as Sep_Revenue,
case when month = "Oct" then revenue end as Oct_Revenue,
case when month = "Nov" then revenue end as Nov_Revenue,
case when month = "Dec" then revenue end as Dec_Revenue
from Department
group by id
上述代码运行有误,我看了下题解,发现还需要加sum,这是因为case when 只会匹配数据集中的一个值,但是有的id在很多个月都会有数据,这里它就不知道该取哪个值,sum的作用就是遍历所有月份,将满足条件的月份放入结果当中。
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
一般来说,遇到这种需要构造新列的题,要么用IF,要么就用Case When。这道题用if也能写,注意也要加sum,这里就不写了,写法几乎一样。
能运行就行。