数据集有三列数据,姓名、月份和数量:
图1
使用sum()函数和over()来实现,如下:
- sum(需要求和的列) over(partition by 分组列 order by 排序列 asc/desc)
- 具体如下:
- select
- *,
- sum(cnt) over(partition by name order by month) as total_cnt
- from
- table
结果如下:同一个name,后一个月份都是前几个月份的累加和
图2
需要稍微骚一点的操作,加上一个限制条件:
- sum(需要求和的列) over(partition by 分组列 order by 排序列 ROWS between 数字 preceding and 数字 following)
- 距离:统计最近三个月的cnt和,包含当前月
- select
- *,
- sum(cnt) over(partition by name order by month ROWS between 2 preceding and 0 following) as total_cnt
- from table_1;
数字:可正可零可负,正往前,负向后;preceding:向前几行;following:向后几行。三个参数交叉组合。
结果如下:其他的都类似,尝试几下就好
图3