LeetCode1179. 重新格式化部门表,使用group by与case聚合处理
Posted Pistachiout
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode1179. 重新格式化部门表,使用group by与case聚合处理相关的知识,希望对你有一定的参考价值。
解题思路
聚合函数本质上就是常见编程语言里的reduce,也就是把一组数据处理成一个单一数据,所以可以这样写:
select id, sum(revenue) as total
from Department
group by id
来表示一个部门的总收入。
这个操作在javascript中类似于这样:
departments.reduce(total, department => total + department.revenue)
max等其它聚合函数同理,都可以找到用reduce表示的等价形式。
那么代码
sum(case month when 'Jan' then revenue end) as Jan_Revenue,
的意思就是说把所有的revenue聚合处理,处理的方法是,如果month的值是Jan,那么结果就是revenue,否则忽略。
代码
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
以上是关于LeetCode1179. 重新格式化部门表,使用group by与case聚合处理的主要内容,如果未能解决你的问题,请参考以下文章