计算累计销售额——(窗口函数)

计算累计销售额,就是设置窗口函数中的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;

你学会了吗~

  • 18
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值