sql 查询先进先出

来源:互联网 发布:人工智能细分领域 编辑:程序博客网 时间:2024/04/28 22:13

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

原创粉丝点击