sql 查询先进先出

declare @tb3 table (商品编号 nvarchar(10),批次号 nvarchar(10),库存数量 int,出库数量 int)
declare @tb1 table (商品编号 nvarchar(10),批次号 nvarchar(10),库存数量 int)
insert into @tb1 select '0001','090801',200
      union all  select '0001','090501',50
      union all  select '0002','090101',30
      union all  select '0002','090701',200
declare @tb2 table (商品编号 nvarchar(10),订货数量 int)
insert into @tb2 select '0001',60
      union all  select '0002',20
--declare @var int
declare c_sor cursor
for
select 商品编号,sum(订货数量)订货数量 from @tb2 group by 商品编号
declare @bh nvarchar(10), @dh int,@bh1 nvarchar(10),@pc nvarchar(10), @kc int
open  c_sor
fetch next from c_sor into @bh,@dh
while @@fetch_status=0
begin
declare sor cursor for select * from @tb1 where 商品编号
=@bh order by 批次号
open sor
fetch next from sor into @bh1,@pc,@kc
insert into @tb3 select @bh, @pc,@kc,case when @kc>@dh then @dh else @kc end
set @dh=@dh-@kc
while @dh>0
 begin
 fetch next from sor into @bh1,@pc,@kc
 insert into @tb3 select @bh, @pc,@kc,case when @kc>=@dh then @dh else @kc end
 set @dh=@dh-@kc
 end
close sor
deallocate sor
fetch next from c_sor into @bh,@dh
end
close c_sor
deallocate c_sor

select * from @tb3  order by 商品编号,批次号 desc

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值