How do I create log of running balance of debits associated to the credits

57 Views Asked by At

I wonder if someone can assist me please and I am at a loss as to how to achieve this without having to iterate through each row with quite a few 'IF' statement.

I have a table of credits and debits and I am trying to create a log for any debits and record with the transaction reference linked to the previous credit(s).

For example, if I had the following row of credit/debit transactions

Transaction Ref Transaction Date Transaction Type Amount
1 1 Jan 2023 Credit 2000
2 1 Apr 2023 Credit 1000
3 1 May 2023 Debit -200
4 1 Aug 2023 Credit 700
5 1 Oct 2023 Debit -1800

Here is a cut down version to setup some test data

CREATE TABLE [TransactionLog] (
    [Customer Id]       VARCHAR (10) NOT NULL,
    [Transaction Ref]   VARCHAR(10) NOT NULL,
    [Transaction Date]  DATETIME     NOT NULL,
    [Transaction Type]  VARCHAR (30) NOT NULL,
    [Amount]            Money  NOT NULL
);
 
CREATE TABLE [OutputDebitLogs] (
    [Customer Id]       VARCHAR (10) NOT NULL,
    [crTransaction Ref] VARCHAR(10) NOT NULL,
    [dbTransaction Ref] VARCHAR(10) NOT NULL,
    [Amount]            Money  NOT NULL
);
 
 
INSERT INTO [TransactionLog] VALUES ('1', '1', '1 Jan 2022', 'Credit', 2000)
INSERT INTO [TransactionLog] VALUES ('1', '2', '1 Apr 2022', 'Credit', 1000)
INSERT INTO [TransactionLog] VALUES ('1', '3', '1 May 2022', 'Debit', -200)
INSERT INTO [TransactionLog] VALUES ('1', '4', '1 Aug 2022', 'Credit', 700)  
INSERT INTO [TransactionLog] VALUES ('1', '5', '1 Oct 2022', 'Debit', -1800)
 

I would like to create an Output log (working from oldest date), where the debit transaction would create a record for the credits that it is being deducted from.

For example - the first debit record (transaction ref 3) would be deducted from the 1 Apr 2023 credit record (Transaction Ref 2) leaving an amount of 800 on Transaction ref 2.

So it would write a record for this as follows

Debit Ref Credit ref Debit Amount
2 3 200

The next debit (Transaction 5) would yield the following records

Debit Ref Credit ref Debit Amount
5 4 700
5 2 800
5 1 300

As you can see this is because the 1800 debit would deduct from the 3 previous credits due to Transaction Ref 2 (1 Apr 2023) already having the 200 deducted.

To have this working correctly the sql script would have to look at what has already been added to the "Output Log so that it knows to include it in the calculations.

I've tried several queries, but am unable to resolve this, so am not too sure if this can be achieved through a combination of a Windows/CTE function.

Hope someone can assist on this.

Thanks in advance Dave

0

There are 0 best solutions below