在ORACLE 11.2中获得连续求和

时间:2015-11-17 03:37:14

标签: oracle sum window-functions running-total

我有一个表格,其中包含2列中的一些(正数)数值,一个用于正数,一个用于负值。

test_table

POSITIVEVALUE | NEGATIVEVALUE
----------------------------------
100 
              | 50
70            |
              | 80
100           | 30

我需要获得每行中行总数的连续总和。我已经通过LAG()尝试了一些事情,结果如下。

查询:

SELECT PositiveValue,
       NegativeValue, 
       RowTotal,
       NVL( (LAG(RowTotal, 1, NULL) OVER (ORDER BY ROWNUM)), 0) AS LagValue, 
       ( NVL( (LAG(RowTotal, 1, NULL) OVER (ORDER BY ROWNUM)), 0)
          + (NVL(RowTotal, 0))) AS SuccessiveSum
FROM(
     SELECT PositiveValue,
            NegativeValue, 
            NVL(PositiveValue, 0) - NVL(NegativeValue, 0) AS RowTotal
      FROM test_table);

结果:

POSITIVEVALUE   NEGATIVEVALUE   ROWTOTAL    LAGVALUE    SUCCESSIVESUM
100                             100         0           100
                50              -50         100         50
70                              70          -50         20
                80              -80         70          -10
100             30              70          -80         -10

如何将结果作为行总数与前一行总和的总和,如下所示?

ROWTOTAL    SUCCESSIVESUM
100         100
-50         50
70          120
-80         40
70          110

2 个答案:

答案 0 :(得分:1)

只是简单的分析总和?

WITH data (POSITIVEVALUE, NEGATIVEVALUE) AS (
    SELECT  100, NULL FROM DUAL UNION ALL
    SELECT NULL,   50 FROM DUAL UNION ALL
    SELECT   70, NULL FROM DUAL UNION ALL
    SELECT NULL,   80 FROM DUAL UNION ALL
    SELECT  100,   30 FROM DUAL
)
SELECT
    ROWTOTAL,
    SUM(ROWTOTAL) OVER (ORDER BY RN) SUCCESSIVESUM
FROM (
    SELECT
        ROWNUM RN,
        NVL(POSITIVEVALUE, 0) - NVL(NEGATIVEVALUE, 0) ROWTOTAL
    FROM
        data)

答案 1 :(得分:0)

        Hello you can try this below code too as it gives decribed result 


        SELECT b.rowtotal,
  b.pos,
  b.neg,
  SUM(DECODE(NVL(b.neg,0),0,b.pos,'-'
  ||b.neg)) over(order by b.rn RANGE UNBOUNDED PRECEDING) cumm
FROM
  (SELECT A.POS-NVL(A.NEG,0) ROWTOTAL,
    A.POS,
    NVL(a.neg,0) neg,
    rownum rn
  FROM
    (SELECT 1000 AS POS,NULL AS NEG FROM dual
    UNION
    SELECT 2000 AS POS,600 AS NEG FROM dual
    UNION
    SELECT 500 AS POS,NULL AS NEG FROM dual
    UNION
    SELECT 1500 AS POS,100 AS NEG FROM dual
    UNION
    SELECT 900 AS POS,50 AS NEG FROM dual
    )A
  )b;

    ----------------------------OUTPUT -----------------------------------------

    ROWTOTAL    POS NEG CUMM
500 500 0   500
850 900 50  450
1000    1000    0   1450
1400    1500    100 1350
1400    2000    600 750

    -----------------------------------------------------------------------------