如何将1条记录数据添加到之前的?

时间:2014-11-28 13:00:17

标签: sql sql-server tsql

我遇到的问题就像我正在通过accountID并根据SP选择一个人的金额细节,例如。

AccountID   AccountTitle  TransactionDate Amount

1           John01        2014/11/28      20

现在,如果同一个帐户ID有第二条或更多条记录,那么它应该添加以前的例如如果accountID 1的第2条记录为40,则金额应显示为60(这样它应该已经添加到20并且在第2条记录中显示总数)

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

浪费了我的时间,无法解决它,所以请帮助我,

3 个答案:

答案 0 :(得分:2)

SQL Server 2012+支持累积总和(这似乎是您想要的):

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轻松完成此操作。

我还修复了你的查询。我不知道你为什么要两次加入Accounts表。此外,表别名使查询更容易编写和读取。

答案 1 :(得分:0)

如果您可以接受所有列的分组,那么这就是答案。

Select AccountID, AccountTitle, TransactionDate, SUM(Payments.Transactions.Amount)
from Payments.Accounts
group by AccountID, AccountTitle, TransactionDate

如果您只想按AccountId分组,则查询为:

Select AccountID, SUM(Payments.Transactions.Amount)
from Payments.Accounts
group by AccountID

在第二个查询中,缺少AccountTitle和TransactionDate,因为它们未在group by子句中使用。要将它们包含在结果中,您必须考虑一个规则来决定使用相同AccountID的多行中的哪一行来获取值AccountTitle和TransactionDate。

答案 2 :(得分:0)

您使用的是什么版本的SQL-Server?这应该可以解决问题:

       Select AccountID, AccountTitle, TransactionData, 
       SUM(Amount) OVER (partiton by AccountID order by TransactionDate) .
  from yourtable group by AccountID, AccountTitle, TransactionData

您使用AccountID获取行组,按交易日期对其进行排序,并按交易日期计算该组中的SUM。

相关问题