I'm working at SQL Server 2008 R2. I'm trying to write a stored procedure which will create new column with current sum of Costs.
I have MyTable
:
ID | Costs
----------------
1 | 5
2 | 3
3 | 2
4 | 4
but I need the third column 'CurrentCosts' with values:
ID | Costs | CurrentCosts
----------------------------------
1 | 5 | 5
2 | 3 | 8
3 | 2 | 10
4 | 4 | 14
and so on.
I tried with:
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
It works but if anybody have better solution, I will be grateful. I got numerous tables with just one result in each and as much tables as I have SELECT commanad in loop. Is there some solution where I will get just one table with all results.
You could use a sub query:
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.