下面为统计截止2020-06-30,近三个月,六个月,十二个月的平均值
直接上代码
select *
from (
select a.cust_id, '2020-06-30' as dt1,
a.dt,
avg(val)over(partition by cust_id order by dt desc) thr_mon_avg,
row_number()over(partition by cust_id order by dt desc) sequence
from (
select '001' cust_id, 100 as val, '2020-06-30' as dt union all
select '001',200, '2020-05-31' union all
select '001',300, '2020-04-30' union all
select '001',400, '2020-03-31' union all
select '001',500, '2020-02-29' union all
select '001',600, '2020-01-31' union all
select '001',700, '2019-12-31' union all
select '001',800, '2019-11-30' union all
select '001',900, '2019-10-31' union all
select '001',1000, '2019-09-30' union all
select '001',1100, '2019-08-31' union all
select '001',1200, '2019-07-31' union all
select '001',1300, '2019-06-30' ) a
where a.dt <= '2020-06-30'
and a.dt >= '2019-07-31' --如果统计的周期更长,可以修改限制条件
) x
where x.sequence in (3,6,12)
利用两个分析函数来解决