计算累计销售额,就是设置窗口函数中的window frame
window frame设置的语法是
-
rows between 上限 and 下限
注意:上限需要在下限之前
它主要涉及的参数如下:
unbound preceding: 表示第1行
n preceding:n表示数字, 表示向上n行, 例: 3 preceding: 表示 向上 3行.
current row: 表示 当前行
n following:n表示数字, 表示向下n行, 例: 3 following :表示 向下 3行.
unbound following : 表示最后1行
例题:计算每个商店截至到每个月的累计销售额
思路:计算每个月的累计销售额,需要使用集合函数sum() +窗口函数,对每个商铺进行分组,对月份进行排序,窗口范围即从第一个月到当前月,即
sum(sales) over(
partition by store_id
order by month
rows between unbounded preceding and current row
)
# 计算每个商店截止到每个月的累计销售额。
# 准备工作 创建表
CREATE TABLE tb_store_sales (
store_id int,
month int,
sales int
)
;
# 插入数据
insert into tb_store_sales
values
(101,1,150),
(101,2,200),
(101,3,250),
(101,4,300),
(101,5,350),
(101,6,400),
(102,1,180),
(102,2,230),
(102,3,280),
(102,4,330),
(102,5,380),
(102,6,430),
(103,1,210),
(103,2,240),
(103,3,290),
(103,4,310),
(103,5,360),
(103,6,390);
# 实现
select
store_id, month, sales,
sum(sales) over(
partition by store_id -- 每个商铺
order by month
rows between unbounded preceding and current row
) total
from tb_store_sales;
你学会了吗~