在Query中计算当前余额以根据事务类型添加/减去?

时间:2018-04-12 06:51:52

标签: sql oracle

这是我的问题:

SELECT track_no,
  (
  CASE
    WHEN credit_type IS NOT NULL
    THEN credit_type
    ELSE debit_type
  END) AS transaction_type,
  (
  CASE WHEN credit_type IS NOT NULL
  then credit_units else
  debit_units end
  ) as units,
  track_dt,
  (select prv_free_units from benf_ewr_track where track_dt='28-JUN-17 04.51.17.291000000 PM')  as openingbalance
FROM benf_ewr_track where track_dt BETWEEN TO_DATE ('2017/06/28', 'yyyy/mm/dd')

结果:

enter image description here

我有3个案例要加/减值。

  1. 期初余额应为之前的日期结算余额。
  2. 当transaction_Type为credit时,使用特定行的单位添加期初余额。
  3. 当transaction_type为借方时,使用特定行的单位减去添加的值。
  4. 注意:此计算需要在查询中计算。

    预期结果:: enter image description here

    示例案例:

    此处,上一个日期的期末余额(27-JUN-17 05.09.48.204000000 PM )是1500。 第二天(28-JUN-17 05.09.48.204000000 PM), 信贷单位是20,它加起来以前的期末余额。所以,期初余额是1520。 然后是借方,减去15给1505。

    任何答案和建议将不胜感激? 谢谢,

1 个答案:

答案 0 :(得分:1)

使用SUM( ... ) OVER ( ORDER BY ... )分析函数:

SELECT *
FROM   (
  SELECT track_no,
         COALESCE( credit_type,   debit_type  ) AS transaction_type,
         COALESCE( credit_units, -debit_units ) as units,
         track_dt,
         SUM( COALESCE( credit_units, 0 ) - COALESCE( debit_units, 0 ) )
           OVER ( ORDER BY track_dt )
           AS Balance
  FROM   benf_ewr_track
)
WHERE  track_dt BETWEEN DATE '2017-06-28' AND SYSDATE