不是,只求三个月,像图片一样,求的是每个月近三个月的数据,本身那个月加上前两个月的
用开窗函数的滑动窗口,前2两行到当前行
with t as (
select '2022-01' dt,1 amt union all
select '2022-02' dt,2 amt union all
select '2022-03' dt,3 amt union all
select '2022-04' dt,4 amt union all
select '2022-05' dt,5 amt union all
select '2022-06' dt,6 amt union all
select '2022-07' dt,7 amt )
select t.*,sum(amt) over(order by dt rows between 2 preceding and current row) 前3月 from t
需要注意的是,统计前两行数据所需要的数据由于已经被where过滤掉了,没统计到,
因此要保证每一行都是前三个月的话,需要先把查询条件放宽,查出数据后再过滤一次