日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

oracle语句求保有率,Oracle之保有量计算(当前记录等于前几条记录之和)

發(fā)布時(shí)間:2023/12/15 编程问答 35 豆豆
生活随笔 收集整理的這篇文章主要介紹了 oracle语句求保有率,Oracle之保有量计算(当前记录等于前几条记录之和) 小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

需求:存在左圖銷量表,要得到右邊的保有量表,保有量等于前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)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。