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
;
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