簡體   English   中英

T-SQL迭代當前總和(按列值)

[英]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
  • “ CurrentCosts”中的第一個值是:5 + 0 = 5
  • “ CurrentCosts”中的第二個值是:5 + 3 = 8
  • “ CurrentCosts”中的第三個值是:8 + 2 = 10
  • “ CurrentCosts”中的第四個值是:10 + 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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM