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?
if this is Oracle, then there are Window functions. you can use LEAD and/or LAG to perform calculations on the current row with respect to prior or upcoming rows (based on sort order)
I used
ROW_NUMBER
AND aCTE
since you're in 2008I'm trying to use this logic with RowNumber and CTE from above. In my scenario, I need the Running Total to be calculated for a combination of two fields: SalesProdLineID and FiscYerPer. Here's what I have coded (in this example, due to the size of the underlying tables I restricted the results to a single Month:
The issue is that once it's got the correct total for the first SalesProdLineID, it simply adds that Running total to the next SalesProdLineID.
--I would use the existing identity column to be 100% sure that I am dealing with the correct transaction.
--also if you change the "Less Than" to "Less Than or Equal To", then you don't have to add the current item:
Totals should be : (Assuming) Starting Balance: 49.25