Tôi đã sử dụng ROW_NUMBER
VÀ CTE
kể từ khi bạn đang ở năm 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