如何选择ID 6-9并在SQL语句中计算运行合计?
这将在图片中显示相同的运行总数,而不是从ID 6开始:

发布于 2016-10-13 03:06:33
如果SQL Server 2012+,则可以使用窗口函数
Declare @YourTable table (ID int,Amount int)
Insert Into @YourTable values (1,80),(2,11),(3,123),(4,47),(5,8),(6,500),(7,49),(8,27),(9,34),(10,56),(11,82),(12,17)
-- If 2012+
Select *
,RunningTotal = sum(Amount) over (Order By ID)
From @YourTable
Where ID between 6 and 9返回
ID Amount RunningTotal
6 500 500
7 49 549
8 27 576
9 34 610如果低于2012年
Select A.ID
,A.Amount
,RunningTotal = sum(B.Amount)
From @YourTable A
Join @YourTable B on (B.ID <=A.ID and B.ID between 6 and 9)
Where A.ID between 6 and 9
Group By A.ID,A.Amount
Order By A.ID发布于 2016-10-13 03:17:42
您可以使用ROWS UNBOUNDED - window函数来计算运行总数
Declare @YourTable table (ID int,Amount int)
Insert Into @YourTable values (1,80),(2,11),(3,123),(4,47),(5,8),(6,500),(7,49),(8,27),(9,34),(10,56),(11,82),(12,17)
select *, sum(amount) over (order by id rows unbounded preceding) as RunningTotal from @yourTable您可以相应地应用条件
https://stackoverflow.com/questions/40006349
复制相似问题