Sqlserver
 sql >> Datenbank >  >> RDS >> Sqlserver

Laufende Summen in einer SQL-Ansicht

Ich habe ROW_NUMBER verwendet UND ein CTE seit du im Jahr 2008 bist

WITH transactionTotal AS
(
   SELECT t.Created, t.Description, t.Credit, t.Debit, t.TransDate, t.TransactionID, a.AccountID
      , ROW_NUMBER() OVER (ORDER BY TransDate ASC) AS RowNumber
      , ( ISNULL(t.Credit, 0) - ISNULL(t.Debit, 0) ) AS TransactionTotal
   FROM dbo.Transactions AS t 
   INNER JOIN dbo.BankAccounts AS a ON t.AccountID = a.AccountID
)
SELECT t.Created, t.Description, t.Credit, t.Debit, t.TransDate, t.TransactionID, t.AccountID
   , ( SELECT SUM(tt.TransactionTotal)
       FROM transactionTotal AS tt
       WHERE tt.RowNumber <= t.RowNumber) AS RunningTotal
FROM transactionTotal AS t
LEFT JOIN transactionTotal AS tt ON t.RowNumber = tt.RowNumber + 1
ORDER BY t.TransDate DESC