sql >> Databasteknik >  >> RDS >> Sqlserver

Löpande summor i en SQL-vy

Jag använde ROW_NUMBER OCH en CTE eftersom du är 2008

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


  1. Ta bort med Left Join i Oracle 10g

  2. MySQL, fel 126:Fel nyckelfil för tabellen

  3. Oracle 11G - Prestandaeffekt av indexering vid insättning

  4. lista över tabeller utan index i sql 2008