繁体   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