I am trying to get running totals in my View in SQL Server 2008
Here is my tables
BankAccounts ------------ AccountID (KEY) Name Created Transactions ------------ TransactionID (KEY) Description Credit Debit TransDate Created AccountID
Here is my query so far..
SELECT t.Created, t.Description, t.Credit, t.Debit, t.TransDate, t.TransactionID, ba.AccountID,
(isnull(t.Credit,0)-isnull(t.Debit,0))+COALESCE((SELECT SUM(isnull(Credit,0)) - SUM(isnull(Debit,0))
FROM Transactions b
WHERE b.TransDate < t.TransDate
and b.AccountID = t.AccountID),0)
AS RunningTotal
FROM Transactions t
INNER JOIN dbo.BankAccounts ba ON t.AccountID = ba.AccountID
What I’m getting is..
TransDate Credit Debit RunningTotal ----------------------- ---------------------- ---------------------- --------------------- 2011-10-08 20:14:00 NULL 12 49.25 2011-10-08 20:14:00 2.11 NULL 63.36 2011-10-07 20:14:00 42.25 NULL 61.25 2011-10-06 20:14:00 NULL 12.25 19 2011-10-05 20:14:00 31.25 NULL 31.25
What it should look like…
TransDate Credit Debit Running Total ----------------------- ---------------------- ---------------------- --------------------- 2011-10-08 00:31:32.957 NULL 12 51.36 2011-10-08 00:31:32.957 2.11 NULL 63.36 2011-10-07 00:31:32.957 42.25 NULL 61.25 2011-10-06 00:31:32.957 NULL 12.25 19 2011-10-05 00:31:32.960 31.25 NULL 31.25
I’m really close.. just seems when there are 2 transactions for same day, it doesn’t calculate it correctly.. any ideas?
I used
ROW_NUMBERAND aCTEsince you’re in 2008