日期:2014-05-17  浏览次数:20324 次

求一个高效的SQL语句
有一个表,存放某时间某商品ID的入库数量
内容如下
ID,quantity,createdate
01  5          2012-01-01
01  15         2012-01-03
01  6          2012-01-08
01  100        2012-05-04
02  3          2012-02-02
02  54         2012-05-06   
……

现在要出库,要求按时间先后顺序来出库,比如01这个商品要出23个(5+15+3),那么就要求把数据库变成
ID,quantity,createdate
01  0          2012-01-01
01  0          2012-01-03
01  3          2012-01-08
01  100        2012-05-04
02  3          2012-02-02
02  54         2012-05-06   
……
有没有什么sql语句,又简单又高效?

------解决方案--------------------
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'



------解决方案--------------------
SQL先进先出的。。
------解决方案--------------------
同意5L的方法