問題描述
我遇到了問題,比如我正在傳遞 accountID 并根據該 SP 選擇一個人的金額詳細信息,例如
i am stuck in problem like i am passing accountID and on the basis of that SP picks amount details of a person e.g.
AccountID AccountTitle TransactionDate Amount
1 John01 2014/11/28 20
現在,如果同一個 accountID 有第二個或更多記錄,那么它應該添加以前的 e.g.如果 accountID 1 的第二條記錄是 40,則金額應顯示 60(這樣它應該已經添加到 20 并在第二條記錄中顯示總數)
now if there is 2nd or more records for same accountID then it should add with previous e.g. if 2nd record for accountID 1 is 40 then amount should display 60 (such that it should be already added to 20 and display total in 2nd record)
AccountID AccountTitle TransactionDate Amount
1 John01 2014/12/30 60 (in real it was 40 but it should show result after being added to 1st record)
同樣適用于更多的記錄
Select Payments.Accounts.AccountID, Payments.Accounts.AccountTitle,
Payments.Transactions.DateTime as TranasactionDateTime,
Payments.Transactions.Amount from Payments.Accounts
Inner Join Payments.Accounts
ON Payments.Accounts.AccountID = Payments.Transactions.Account_ID
Inner Join Payments.Transactions
where Payments.Transactions.Account_ID = 1
它浪費了我的時間,無法再解決它,所以請幫助我,
it has wasted my time and can't tackle it anymore, so please help me,
推薦答案
SQL Server 2012+ 支持累積總和(這似乎是你想要的):
SQL Server 2012+ supports cumulative sums (which seems to be what you want):
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;
在早期版本的 SQL Server 中,您可以使用相關子查詢或使用 cross apply
最輕松地做到這一點.
In earlier versions of SQL Server you can most easily do this with a correlated subquery or using cross apply
.
我還修復了您的查詢.我不知道你為什么兩次加入 Accounts 表.此外,表別名使查詢更易于編寫和閱讀.
I also fixed your query. I don't know why you were joining to the Accounts table twice. Also, table aliases make queries much easier to write and to read.
這篇關于如何將 1 條記錄數據添加到以前的數據?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!