Oracle、Hive 统计三个月,六个月,九个月,十二个月的平局值

本文展示了截至2020年6月30日,客户001的月度平均值计算方法,通过三个时间段(3个月、6个月、12个月)的数据集,使用SQL查询和窗口函数,揭示了客户的消费行为变化趋势。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

下面为统计截止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)

利用两个分析函数来解决

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值