我在SQL Server 2008 R2上工作。我正在尝试编写一个存储过程,该过程将创建具有当前总成本的新列。
我有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 commanad。是否有一些解决方案,我将只获得一个包含所有结果的表。
答案 0 :(得分:3)
您可以使用子查询:
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
答案 1 :(得分:0)