在SQL视图中运行总计

jae*_*kie 2 sql sql-server aggregate-functions totals sql-server-2008

我试图在SQL Server 2008的View中运行总计

这是我的桌子

BankAccounts
------------
AccountID (KEY)
Name
Created

Transactions
------------
TransactionID (KEY)
Description
Credit
Debit
TransDate
Created
AccountID

这是我到目前为止的查询..

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

我得到的是......

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

应该是什么样子......

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

我真的很接近..只是当同一天有2笔交易,它没有正确计算..任何想法?

Ada*_*ger 6

我从2008年开始使用ROW_NUMBERAND aCTE

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
Run Code Online (Sandbox Code Playgroud)