oracle语句求保有率,Oracle之保有量计算(当前记录等于前几条记录之和)
需求:存在左圖銷量表,要得到右邊的保有量表,保有量等于前12月銷量和。
年
月
銷量
年
月
保有量
2010
1
4
2010
1
4
2010
2
4
2010
2
8
2010
3
4
2010
3
16
2010
4
4
2010
4
20
2010
5
4
2010
5
24
2010
6
4
2010
6
28
2010
7
4
2010
7
32
2010
8
4
2010
8
36
2010
9
4
2010
9
40
2010
10
4
2010
10
44
2010
11
4
2010
11
48
2010
12
4
2010
12
52
2011
1
4
2011
1
52
2011
2
4
2011
2
52
2011
3
4
2011
3
52
2011
4
4
2011
4
52
2011
5
4
2011
5
52
2011
6
4
2011
6
52
解答:創(chuàng)建例表,便于測試
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
--計(jì)算保有量(保有量等于前12個(gè)月內(nèi)的銷量和)
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
--利用分析函數(shù)也可以:
--方法一
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
以上兩個(gè)分析函數(shù)的使用存在錯(cuò)誤,保有量的計(jì)算是按鈕年月前推12個(gè)月(即一年內(nèi)),實(shí)際業(yè)務(wù)中不能保證每個(gè)月都有數(shù)據(jù)(即每個(gè)月都有銷量),如果我們能確保表中每個(gè)月都有銷量的話(或?qū)⑷笔〉脑路輼?gòu)造成0銷量也可)上述兩個(gè)分析函數(shù)的方法可以使用。使用range窗體子句才是正解,如下:
SELECT y,m,n,SUM(n)over(order by y,mrange between 11 preceding and 0 following) QTY.
FROM tsales
分析函數(shù)中窗口子句rows和range的區(qū)別就是前者以記錄數(shù)分窗,后者以字段值分窗;
總結(jié)
以上是生活随笔為你收集整理的oracle语句求保有率,Oracle之保有量计算(当前记录等于前几条记录之和)的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: oracle管理认证方式,关于Oracl
- 下一篇: 学php5还是php7,学习猿地-php