[英]T-SQL iterative current sum by column value
我正在使用SQL Server 2008 R2。 我正在嘗試編寫一個存儲過程,該過程將使用當前的Costs總和創建一個新列。
我有MyTable
:
ID | Costs
----------------
1 | 5
2 | 3
3 | 2
4 | 4
但我需要帶有值的第三列“ CurrentCosts”:
ID | Costs | CurrentCosts
----------------------------------
1 | 5 | 5
2 | 3 | 8
3 | 2 | 10
4 | 4 | 14
等等。
我嘗試過:
declare @ID INT
declare @current_cost int
declare @running_cost int
select @ID = min( ID ) from MyTable
set @running_cost = 0
set @current_cost = 0
while @ID is not null
begin
select ID, Costs, @running_cost as 'CurrentCosts' from MyTable where ID = @ID
select @ID = min( ID ) from MyTable where ID > @ID
select @current_cost = Costs from MyTable where ID = @ID
set @running_cost += @current_cost
end
它可以工作,但是如果有人有更好的解決方案,我將不勝感激。 我得到了很多表,每個表中只有一個結果,而循環中的SELECT命令也是如此。 是否有一些解決方案,我將只獲得一張包含所有結果的表。
您可以使用子查詢:
SELECT ID, Costs,
(SELECT Sum(Costs)
FROM dbo.MyTable t2
WHERE t2.ID <= t1.ID) AS CurrentCosts
FROM dbo.MyTable t1
ID COSTS CURRENTCOSTS
1 5 5
2 3 8
3 2 10
4 4 14
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.