oracle 利用窗口函数计算合计、上月、下月及累计值等

数据准备:

     create table TEST_GROUP_TABLE
(
  t_year   NUMBER,
  t_month  NUMBER,
  quantity NUMBER
);

 insert into test_group_table values(2012,1,29);

       insert into test_group_table values(2012,1,39);

       insert into test_group_table values(2012,2,11);

       insert into test_group_table values(2012,3,12);

       insert into test_group_table values(2013,1,10);

       insert into test_group_table values(2013,2,20);

       insert into test_group_table values(2013,3,30);

       insert into test_group_table values(2013,4,40);

--根据年份分组计算最小(大)数量及及最小(大)数量的月份

select t.t_year,

               t.t_month,
               sum(quantity) qty,
               first_value(sum(quantity)) over(partition by t_year order by sum(quantity)) min_qty,
               first_value(t_month) over(partition by t_year order by sum(quantity)) min_month,
               first_value(sum(quantity)) over(partition by t_year order by sum(quantity) desc) max_qty,
               first_value(t_month) over(partition by t_year order by sum(quantity) desc) max_month,
               rank() over(partition by t_year order by sum(quantity) desc) rank_1
          from test_group_table t
         group by t.t_year, t.t_month;

--根据年份分组计算当月合计数量,上月合计数量,下月合计数量
select t.t_year,
       t.t_month,
       sum(quantity) curr_month,
       lag(sum(quantity)) over(partition by t_year order by t_month) last_month,
       lead(sum(quantity)) over(partition by t_year order by t_month) next_month
  from test_group_table t
 group by t.t_year, t.t_month;

--根据年份分组,计算前n月至当月的合计数量
select t.t_year,
       t.t_month,
       sum(quantity),
       sum(sum(quantity)) over(partition by t_year order by t_month rows between unbounded preceding and current row) agg_qty
  from test_group_table t

 group by t.t_year, t.t_month;

--根据年份分组,计算上月、当月和下月的合计数量

select t.t_year,
       t.t_month,
       sum(quantity),
       sum(sum(quantity)) over(partition by t_year order by t_month rows between 1 preceding and 1 following) agg_qty
  from test_group_table t
 group by t.t_year, t.t_month;

  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值