为什么我的记录为所有记录返回相同的金额?

时间:2014-11-28 16:36:24

标签: sql sql-server tsql

我正在通过accountID,并根据SP挑选一个人的数量细节,例如

AccountID   AccountTitle  TransactionDate Amount RunningAmount
1           John01        2014/11/28      20        20

现在,如果同一accountID有第二条或更多条记录,那么它应该添加前一条记录,例如如果accountID 1的第2条记录是40,那么RunningAmount应显示60,但金额应显示原始,即40

AccountID   AccountTitle  TransactionDate Amount RunningAmount
    1           John01        2014/12/30    40      60

同样需要进一步记录。

Select 
    a.AccountID, a.AccountTitle, t.DateTime as TranasactionDateTime, 
    t.Amount,
    sum(t.Amount) over (partition by t.Account_Id order by t.DateTime) as RunningAmount    
from 
    Payments.Accounts a Inner 
Join
    Payments.Transactions t on a.AccountID = t.Account_ID
where 
    t.Account_ID = 1;

返回此结果:

AccountID   AccountTitle    TranasactionDateTime    Amount  RunningAmount
1           Test Account    2014-11-28 09:22:00     500.00    1300.00
1           Test Account    2014-11-28 01:12:00     800.00    1300.00

但我希望它像这样

AccountID   AccountTitle    TranasactionDateTime    Amount  RunningAmount
1           Test Account    2014-11-28 09:22:00     500.00    500.00
1           Test Account    2014-12-21 01:12:00     800.00    1300.00
1           Test Account    2014-10-11 21:11:01     100.00    1400.00

1 个答案:

答案 0 :(得分:0)

您的查询应该是您想要的。你可以更加强调:

   sum(t.Amount) over (partition by t.Account_Id
                       order by t.DateTime
                       rows between unbounded preceding and current row
                      ) as RunningAmount