当前位置:  开发笔记 > 编程语言 > 正文

在oracle查询中计算运行余额

如何解决《在oracle查询中计算运行余额》经验,为你挑选了1个好方法。

我有这样的数据

id    cp_id   amount_a       amount_b
CCP1  TTP01   10.000.000     2.000.000
CCP1  TTP02   10.000.000     3.000.000
CCP1  TTP03   10.000.000     1.000.000
CCP1  TTP04   10.000.000       500.000
CCP2  TTP05    5.000.000     1.000.000
CCP2  TTP06    5.000.000     2.000.000
CCP3  TTP07    1.000.000       500.000 

我希望结果数据添加一列running_balance,如下所示

id       amount_a       amount_b      running_balance
CCP1   10.000.000     2.000.000     8.000.000
CCP1   10.000.000     3.000.000     5.000.000
CCP1   10.000.000     1.000.000     4.000.000
CCP1   10.000.000       500.000     3.500.000
CCP2    5.000.000     1.000.000     4.000.000
CCP2    5.000.000     2.000.000     2.000.000
CCP3    1.000.000       500.000       500.000 

我已经做了这样的查询

/* Formatted on 1/26/2017 2:50:06 PM (QP5 v5.115.810.9015) */
  SELECT   B.NO_KLAIM AS id,
           a.amount AS amount_a,
           B.AMOUNT AS amount_b,
           SUM (A.AMOUNT) OVER (ORDER BY B.AMOUNT ROWS UNBOUNDED PRECEDING)
              AS running_balance
    FROM      TRX_TITIPAN A
           JOIN
              TRX_KLAIM_TITIPAN B
           ON A.NO_RESI_TITIPAN = B.NO_RESI_TITIPAN
GROUP BY   B.NO_KLAIM, B.AMOUNT, a.amount

但结果没有计算amount_a,只是为amount_b运行总计.

**更新:我已经对我的查询进行了更新.

 /* Formatted on 1/26/2017 2:50:06 PM (QP5 v5.115.810.9015) */
      SELECT   B.NO_KLAIM AS id,
               a.amount AS amount_a,
               B.AMOUNT AS amount_b,
               NVL (TITIP.AMOUNT, 0)
               - SUM (NVL (KLAIM.AMOUNT, 0))
                    OVER (PARTITION BY TITIP.AMOUNT
                          ORDER BY TITIP.NO_RESI_TITIPAN,
                                   KLAIM.NO_KLAIM,
                                   TITIP.AMOUNT,
                                   KLAIM.AMOUNT asc
                          ROWS UNBOUNDED PRECEDING) as running_balance
        FROM      TRX_TITIPAN A
               JOIN
                  TRX_KLAIM_TITIPAN B
               ON A.NO_RESI_TITIPAN = B.NO_RESI_TITIPAN
    GROUP BY   B.NO_KLAIM, B.AMOUNT, a.amount

使用具有特定ID的WHERE id = ....条件时,运行余额正常工作.当我删除WHERE id = ....条件时它出错了.



1> Boneist..:

我想你是在追求:

SELECT   B.NO_KLAIM AS id,
         a.amount AS amount_a,
         B.AMOUNT AS amount_b,
         a.amount - SUM (B.AMOUNT) 
                   OVER (partition by b.no_klaim ORDER BY B.cp_id ROWS UNBOUNDED PRECEDING)
              AS running_balance
FROM      TRX_TITIPAN A
           JOIN
              TRX_KLAIM_TITIPAN B
           ON A.NO_RESI_TITIPAN = B.NO_RESI_TITIPAN

推荐阅读
谢谢巷议
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有