现在有这样一个需求:一张表orders中记录了每个用户消费的明细(时间、金额),现在需要求出每个用户当月的消费总金额和总的消费总金额。如何求呢?
1.orders表结构
1 | name string |
2.分析
统计的当月总金额这个汇总值,那么对name和month进行分组sum(amount)即可得到。
统计总金额,那么只需对name进行分组即可。
方法一
分别求出上面2个汇总值,然后进行join就行:1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21select
name,
month_amount,
sum_amount
from (
select
name,
month(dt) as cur_month,
sum(amount) as month_amount
from orders
group by name, month(dt);
) t1
join
(
select
name,
sum(amount) as sum_amount
from orders
group by name
) t2
on t1.name = t2.name;方法二
使用开窗函数,不在需要表join了:1
2
3
4
5select
name,
sum(amount) over(partition by name, month(dt)) as month_amount,
sum(amount) over(partition by name) as sum_amount
from orders
开窗函数是不是简单多了?
If somethings in life brings you joy, then you simple have to do it, regardless of what people say.
—《海蒂与爷爷》
书山有路勤为径,学海无涯苦作舟。
欢迎关注微信公众号:【程序员写书】
喜欢宠物的朋友可以关注:【电巴克宠物Pets】
一起学习,一起进步。
