SELECT
T1.[CustomerID],
T1.TransactionType,
YEAR(T1.TransactionDate) AS TranactionYear,
MONTH(T1.TransactionDate) AS TranactionMonth,
SUM(T1.Credit) AS Credits,
SUM(T1.Debit) AS Debits,
(
SELECT
SUM(Credit - Debit)
FROM
TransactionsCD AS T2
WHERE
T2.CustomerID = T1.CustomerID
AND T2.TransactionType = T1.TransactionType
AND FORMAT(T2.TransactionDate, "yyyymm") <= FORMAT(T1.TransactionDate, "yyyymm")
) AS Balance
FROM
TransactionsCD AS T1
GROUP BY
T1.[CustomerID],
T1.TransactionType,
YEAR(T1.TransactionDate),
MONTH(T1.TransactionDate),
FORMAT(T1.TransactionDate, "yyyymm");