Oracle之保有量计算(当前记录等于前几条记录之和)

 

需求:存在左图销量表,要得到右边的保有量表,保有量等于前12月销量和。

 

销量 保有量
201014 201014
201024 201028
201034 2010316
201044 2010420
201054 2010524
201064 2010628
201074 2010732
201084 2010836
201094 2010940
2010104 20101044
2010114 20101148
2010124 20101252
201114 2011152
201124 2011252
201134 2011352
201144 2011452
201154 2011552
201164 2011652

 

解答:创建例表,便于测试

create table tsales(y,m,n)--年,月,销量
as select  2010,  1,  4 from dual union all
select  2010,  2,  4 from dual union all
select  2010,  3,  4 from dual union all
select  2010,  4,  4 from dual union all
select  2010,  5,  4 from dual union all
select  2010,  6,  4 from dual union all
select  2010,  7,  4 from dual union all
select  2010,  8,  4 from dual union all
select  2010,  9,  4 from dual union all
select  2010,  10,  4 from dual union all
select  2010,  11,  4 from dual union all
select 2010, 12, 4 from dual union all
select  2011,  1,  4 from dual union all
select  2011,  2,  4 from dual union all
select  2011,  3,  4 from dual union all
select  2011,  4,  4 from dual union all
select  2011,  5,  4 from dual union all
select 2011, 6, 4 from dual

--计算保有量(保有量等于前12个月内的销量和)
select t1.*,(select sum(t2.n)
             from tsales t2
            where (t2.y = t1.y and t2.m <= t1.m)
               or (t2.y = t1.y - 1 and t2.m > t1.m)
           ) as 保有量 from tsales t1

 

--利用分析函数也可以:

--方法一

select y,m,n,n+LAG(n,11,0)over(order by y,m)+LAG(n,10,0)over(order by y,m)+LAG(n,9,0)over(order by y,m)+
LAG(n,8,0)over(order by y,m)+LAG(n,7,0)over(order by y,m)+LAG(n,6,0)over(order by y,m)+
LAG(n,5,0)over(order by y,m)+LAG(n,4,0)over(order by y,m)+LAG(n,3,0)over(order by y,m)+
LAG(n,2,0)over(order by y,m)+LAG(n,1,0)over(order by y,m) as 保有量from tsales

 


--方法二

SELECT y,m,n,SUM(n)over(order by y,m rows between 11 preceding and 0 following) QTY
FROM tsales

 

以上两个分析函数的使用存在错误,保有量的计算是按钮年月前推12个月(即一年内),实际业务中不能保证每个月都有数据(即每个月都有销量),如果我们能确保表中每个月都有销量的话(或将缺省的月份构造成0销量也可)上述两个分析函数的方法可以使用。使用range窗体子句才是正解,如下:

SELECT y,m,n,SUM(n)over(order by y,m range between 11 preceding and 0 following) QTY.
FROM tsales

 

 

分析函数中窗口子句rows和range的区别就是前者以记录数分窗,后者以字段值分窗;

 

 

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值