日期:2014-05-17 浏览次数:20702 次
ID FirstQuantity ChangeQuantity FinalQuantity
1 0 10 10
1 10 20 30
1 30 30 60
create table tc(ID int, Quantity int)
insert into tc
select 1 ,10 union all
select 1 ,20 union all
select 1 ,30
go
;with t
as
(
select *,
ROW_NUMBER() over(partition by id order by @@servername) rownum
from tc
)
select ID,
FirstQuantity,
ChangeQuantity,
FirstQuantity+ChangeQuantity as inalQuantity
from
(
select ID,
case when rownum = 1 then 0
else (select SUM(Quantity) from t t2
where t2.ID = t1.id and t2.rownum < t1.rownum)
end as FirstQuantity,
Quantity as ChangeQuantity
from t t1
)tt
/*
ID FirstQuantity ChangeQuantity inalQuantity
1 0 10 10
1 10 20 30
1 30 30 60
*/