Skip to Main Content
  • Questions
  • Running balance for debits and credits

Breadcrumb

Question and Answer

Chris Saxon

Thanks for the question, Paul .

Asked: July 16, 2022 - 3:04 pm UTC

Last updated: July 18, 2022 - 12:34 pm UTC

Version: 19.2

Viewed 10K+ times! This question is

You Asked


I am trying to keep track of debits and credits, which I believe I got semi correct.

In addition, I want to keep a running balance column for EVERY transaction. For credits the balances should be subtracted and for debits transactions should be added to the balance but I'm having difficulty incorporating this logic.

For my test CASE I want to produce the following results:

For July 10 the balance should be -2000, (0 - 2000), for july 11 balance should be -4000 (-2000 - -2000), July 12 balance -2100 (-4000 - 1100 + 3000.

Note I grouped the VALUES by date for legibility purposes I want every transaction listed with a running balance next to it in a new column.

Thanks for your help. My test CASE.

create table t(trans_id NUMBER, type varchar2(1),amt int,dt date);

 insert into t values(1,'C',1000,to_date('10-Jul-2022','dd-mon-yyyy'));
 insert into t values(2,'C',1200,to_date('10-Jul-2022','dd-mon-yyyy'));
 insert into t values(3,'C',2000,to_date('11-Jul-2022','dd-mon-yyyy'));
 insert into t values(4,'D',1000,to_date('12-Jul-2022','dd-mon-yyyy'));
 insert into t values(5,'D',2000,to_date('12-Jul-2022','dd-mon-yyyy'));
 insert into t values(6,'C',1100,to_date('12-Jul-2022','dd-mon-yyyy'));


WITH  daily_summary  AS
(
    SELECT     dt
    ,     SUM (DECODE (type, 'C', amt, 0))    AS credit_total
    ,     SUM (DECODE (type, 'D', amt, 0))    AS debit_total
    FROM     t
    GROUP BY dt
)
SELECT   d.*
,     SUM (credit_total - debit_total)
       OVER (ORDER BY dt) AS balance_to_date
FROM    daily_summary d
ORDER BY dt
;

and Chris said...

Though the data in the table don't quite match the example calculations you've provided, it looks to me like all you need to do is invert the values in the subtraction:

WITH  daily_summary  AS
(
    SELECT     dt
    ,     SUM (DECODE (type, 'C', amt, 0))    AS credit_total
    ,     SUM (DECODE (type, 'D', amt, 0))    AS debit_total
    FROM     t
    GROUP BY dt
)
SELECT d.*
,      SUM ( debit_total-credit_total )
         OVER (ORDER BY dt) AS balance_to_date
FROM   daily_summary d
ORDER BY dt;

DT                CREDIT_TOTAL DEBIT_TOTAL BALANCE_TO_DATE
----------------- ------------ ----------- ---------------
10-JUL-2022 00:00         2200           0           -2200
11-JUL-2022 00:00         2000           0           -4200
12-JUL-2022 00:00         1100        3000           -2300


Is this answer out of date? If it is, please let us know via a Comment

More to Explore

Analytics

Analytic SQL got you confused? Check out Connor McDonald's complete video course.