产品 数量 日期 单据号
a 10 9.1 001
a 3 9.2 002
a 4 9.3 003
a 2 9.4 004
以日期升序排 数量总额减去14后的结果
产品 数量 日期 单据号
a 3 9.3 003
a 2 9.4 004
这个sql 怎么写?
方法一:create table tb(产品 varchar(2), 数量 int, 日期 varchar(4), 单据号 varchar(4))
insert into tb
select 'a',10,'9.1','001' union all
select 'a',3,'9.2','002' union all
select 'a',4,'9.3','003' union all
select 'a',2,'9.4','004'
select * from tb
declare @num int,@t int
set @num=14
set @t=0
update tb set 数量=case when 数量>=@num then 数量-@num else 0 end,@num=@num-@t,
@t=case when 数量>=@num then @num else 数量 end
select * from tb where 数量>0
drop table tb
方法二:(未测试)
select t.p,case when (select sum(qty) from @t where dt<t.dt)<=14 then (select sum(qty) from @t where dt<=t.dt)-14 else qty end as qty,t.dt,t.num
from @t t
where (select sum(qty) from @t where dt<=t.dt)>14