日期:2014-05-17 浏览次数:20378 次
declare @ct int
set @ct=23
;with tb(ID,quantity,createdate)
as(
select '01',5,'2012-01-01' union all
select '01',15,'2012-01-03' union all
select '01',6,'2012-01-08' union all
select '01',100,'2012-05-04' union all
select '02',3,'2012-02-02' union all
select '02',54,'2012-05-06'
),tb1 as(
select *,ct=@ct,row=row_number()over(order by createdate) from tb where id='01'
),
cte as(
select ID,quantity=(case when ct<=0 then quantity when ct>=quantity then 0 else quantity-ct end),createdate,ct=ct-quantity,row from tb1 where row=1
union all
select t.id,quantity=(case when c.ct<=0 then t.quantity when c.ct>=t.quantity then 0 else t.quantity-c.ct end),t.createdate,c.ct-t.quantity,t.row from tb1 t join cte c on c.row+1=t.row
)
select ID,quantity,createdate from cte
union all
select * from tb where id!='01'