Sql 如何将1条记录数据添加到上一条记录?

Sql 如何将1条记录数据添加到上一条记录?,sql,sql-server,tsql,Sql,Sql Server,Tsql,我被困在问题中,就像我传递accountID一样,并根据该SP选择一个人的金额详细信息,例如 AccountID AccountTitle TransactionDate Amount 1 John01 2014/11/28 20 现在,如果同一accountID有第二条或多条记录,则应将其与上一条记录相加。例如,如果accountID 1的第二条记录为40,则金额应显示为60(这样,应将其添加到20,并在第二条记录中显示总计) 进一步的记录

我被困在问题中,就像我传递accountID一样,并根据该SP选择一个人的金额详细信息,例如

AccountID   AccountTitle  TransactionDate Amount

1           John01        2014/11/28      20
现在,如果同一accountID有第二条或多条记录,则应将其与上一条记录相加。例如,如果accountID 1的第二条记录为40,则金额应显示为60(这样,应将其添加到20,并在第二条记录中显示总计)

进一步的记录也是如此

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

它浪费了我的时间,无法再处理它,所以请帮助我,

如果您可以接受按所有列进行分组,这里是答案

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,因为它们未在GROUPBY子句中使用。要将它们包括在结果中,您必须考虑一个规则来决定使用多行中具有相同AccountID的哪一行来获取AccountTitle和TransactionDate值。

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

在早期版本的SQL Server中,您可以通过相关子查询或使用
交叉应用
轻松实现这一点


我也修正了你的问题。我不知道你为什么两次加入会计表。此外,表别名使查询更易于编写和读取。

您使用的是什么版本的SQL Server?这应该可以做到:

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

您使用AccountID获取一组行,按交易日期对它们进行排序,并按交易日期对该组中的总和进行计数。

问题是要求一个运行总数,而不是一个总数。
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;
       Select AccountID, AccountTitle, TransactionData, 
       SUM(Amount) OVER (partiton by AccountID order by TransactionDate) .
  from yourtable group by AccountID, AccountTitle, TransactionData