
算欠料数的规则,先满足日期小的。以此类推
------解决思路----------------------
declare @tab table(日期 date,物料 varchar(30),当前库存 int,需求 int)
insert into @tab
select '20150601','A001',100,20 union all
select '20150602','A001',100,50 union all
select '20150603','A001',100,500
;with t1 as
(select *,row_number() over(partition by [物料] order by 日期) as rn from @tab)
,t2 as
(
select 日期,物料,当前库存,case when 当前库存>=需求 then 0 else 当前库存-需求 end as 欠数,rn,当前库存-需求 剩余 from t1 where rn=1
union all
select t1.日期,t1.物料,t1.当前库存,case when t2.剩余>=t1.需求 then 0 else t2.剩余-需求 end as 欠数,t1.rn,t2. 剩余-t1.需求 from t1
join t2 on t1.rn=t2.rn+1 and t1.物料=t2.物料
)
select 日期,物料,当前库存,欠数 from t2