三、窗口函数进阶--滚动统计(累积/均值)
考虑前面提到的第2个需求:列出每月的订单总额以及截至到当前月的订单总额。也就是说2月份的记录要显示当月的订单总额和1,2月份订单总额的和。3月份要显示当月的订单总额和1,2,3月份订单总额的和,依此类推。
很明显这个需求需要在统计第N月的订单总额时,还要再统计这N个月来的订单总额之和。想想上面的语句,假如我们能够把and unbounded following换成代表当前月份的逻辑多好啊!很幸运的是Oracle考虑到了我们这个需求,为此我们只需要将语句稍微改成: current row就可以了。
SQL> select month,
sum(total_sales) month_sales,
sum(sum(total_sales)) over (order by month
rows between unbounded preceding and current row ) total_sale
from win_order group by month;
MONTH MONTH_SALES TOTAL_SALE
----- ----------- ----------
1 623141 623141
2 423124 1046265
3 323214 1369479
4 212314 1581793
5 654314 2236107
6 122134 2358241
7 859234 3217475
8 752314 3969789
9 365314 4335103
10 265314 4600417
11 563114 5163531
12 595314 5758845
12 rows selected
下面的结果一样:
SQL> select month,
2 sum(total_sales) month_sales,
3 sum(sum(total_sales)) over (order by month) total_sale
4 from win_order group by month
5 ;
MONTH MONTH_SALES TOTAL_SALE
----- ----------- ----------
1 623141 623141
2 423124 1046265
3 323214 1369479
4 212314 1581793
5 654314 2236107
6 122134 2358241
7 859234 3217475
8 752314 3969789
9 365314 4335103
10 265314 4600417
11 563114 5163531
12 595314 5758845
12 rows selected
因此,rows between unbounded preceding and current row 为窗口默认值!
现在我们能得到滚动的销售总额了!下面这个统计结果看起来更加完美,它展现了所有我们需要的数据
SQL> select month,
sum(total_sales) month_sales,
sum(sum(total_sales)) over(order by month
rows between unbounded preceding and current row) total_sales,
sum(sum(total_sales)) over(order by month
rows between unbounded preceding and unbounded following) total_sales
from win_order group by month
8 ;
MONTH MONTH_SALES TOTAL_SALES TOTAL_SALES
----- ----------- ----------- -----------
1 623141 623141 5758845
2 423124 1046265 5758845
3 323214 1369479 5758845
4 212314 1581793 5758845
5 654314 2236107 5758845
6 122134 2358241 5758845
7 859234 3217475 5758845
8 752314 3969789 5758845
9 365314 4335103 5758845
10 265314 4600417 5758845
11 563114 5163531 5758845
12 595314 5758845 5758845
12 rows selected
在一些销售报表中我们会时常看到求平均值的需求,有时可能是针对全年的数据求平均值,有时会是针对截至到当前的所有数据求平均值。很简单,只需要将:
sum(sum(tot_sales))换成avg(sum(tot_sales))即可。
SQL> select month,
2 avg(total_sales) month_avg_sales,
3 avg(avg(total_sales)) over(order by month
4 rows between unbounded preceding and current row) current_avg_sales,
5 avg(avg(total_sales)) over(order by month
6 rows between unbounded preceding and unbounded following) avg_sale
7 from win_order
8 group by month
9 ;
MONTH MONTH_AVG_SALES CURRENT_AVG_SALES AVG_SALE
----- --------------- ----------------- ----------
1 623141 623141 479903.75
2 423124 523132.5 479903.75
3 323214 456493 479903.75
4 212314 395448.25 479903.75
5 654314 447221.4 479903.75
6 122134 393040.166666667 479903.75
7 859234 459639.285714286 479903.75
8 752314 496223.625 479903.75
9 365314 481678.111111111 479903.75
10 265314 460041.7 479903.75
11 563114 469411.909090909 479903.75
12 595314 479903.75 479903.75
