Oracle滚动或运行总计按月计算

时间:2012-01-19 19:20:53

标签: sql oracle

目标:每个月末所有报表的滚动/运行总计。

代码:

select 
    TRUNC(ACTHX.STMT_HX_STMT_DATE, 'MM') AS MNTH, 
    COUNT(ACTHX.INVOICE) as STMTS
from ACTHX
group by
    TRUNC(ACTHX.STMT_HX_STMT_DATE, 'MM')
ORDER BY
    TRUNC(ACTHX.STMT_HX_STMT_DATE, 'MM')

当前输出:

MNTH        STMTS
7/1/2009    1
10/1/2010   4
6/1/2011    26
9/1/2011    211
10/1/2011   163
11/1/2011   119

期望的输出:

MNTH        STMTS
7/1/2009    1
10/1/2010   5
6/1/2011    31
9/1/2011    242
10/1/2011   405
11/1/2011   524

2 个答案:

答案 0 :(得分:12)

听起来你想要跑步总数。您可以使用分析SUM函数。

select mnth,
       sum(stmts) over (order by mnth) stmts
  from (select TRUNC(ACTHX.STMT_HX_STMT_DATE, 'MM') AS MNTH, 
               COUNT(ACTHX.INVOICE) as STMTS
          from ACTHX
         group by TRUNC(ACTHX.STMT_HX_STMT_DATE, 'MM'))
 ORDER BY mnth

答案 1 :(得分:2)

提供相同滚动总计而没有子查询的替代解决方案。

SELECT
        DISTINCT TRUNC(ACTHX.STMT_HX_STMT_DATE,'MM') AS MNTH
        ,count(ACTHX.INVOICE) OVER (ORDER BY TRUNC(ACTHX.STMT_HX_STMT_DATE,'MM')) AS STMTS
    FROM  ACTHX
    ORDER BY
        TRUNC(ACTHX.STMT_HX_STMT_DATE,'MM')