需求如下:
a 需求 30
b 需求 50
c 需求 20
d 需求 80
已有物料
集合1 数量10 适用于A
集合2 数量20 适用于AB
集合3 数量3 适用于ABC
集合4 数量6 适用于AC
集合5 数量2 适用于BC
集合6 数量2 适用于B
集合7 数量1 适用于C我要怎样报出一个差缺数来,使我采购的数量最少?

解决方案 »

  1.   

    你的意思是不是所 集合2 数量20 适用ab 也就是说a,b都可以用没有多少之分
      

  2.   

    试试这个
    --测试数据
    declare @t table (project varchar(10),num int)
    insert @t
    select 'a',30 union
    select 'b',50 union
    select 'c',20 union
    select 'd',80 declare @t1 table (groups varchar(10),num int,fits varchar(10),fit varchar(10))
    insert @t1
    select '集合1',10,'A',' ' union 
    select '集合2',20,'AB',' ' union 
    select '集合3',3,'ABC',' ' union  
    select '集合4',6,'AC',' ' union  
    select '集合5',2,'BC',' ' union  
    select '集合6',2,'B',' ' union  
    select '集合7',1,'C',' ' --精确匹配
    select a.*,num1=a.num-isnull(sum(b.num),0) into #a from @t a
    left join @t1 b on a.project=b.fits
    group by a.project,a.num
    update a set a.fit=b.project from @t1 a inner join @t b on a.fits=b.project--模糊匹配
    declare @project varchar(10),@num int,@tempnum int
    select @tempnum =0
    declare prj cursor scroll for select project,num1 from #a order by num1 desc
    open prj
    fetch absolute 1 from prj into @project,@num
    while @@fetch_status=0
    begin
    select * into #t from @t1 where fits like '%'+@project+'%' and fit=' ' and num<=@num order by num desc
    update #t set  fit=case when @tempnum+num<=@num then @project else fit end,
    @tempnum=@tempnum+num
    update a set a.fit=b.fit from @t1 a 
    inner join #t b on a.groups=b.groups
    drop table #t
    set @tempnum=0
    fetch next from prj into @project,@num
    end
    close prj
    deallocate prjselect * from @t1
    --差缺数
    select a.project,a.num,a.num-isnull(sum(b.num),0) 差缺数 from @t a
    left join @t1 b on a.project=b.fit
    group by a.project,a.numdrop table #a
    /*结果
    groups     num         fits       fit        
    ---------- ----------- ---------- ---------- 
    集合1        10          A          a
    集合2        20          AB         b
    集合3        3           ABC        b
    集合4        6           AC         a
    集合5        2           BC         b
    集合6        2           B          b
    集合7        1           C          c(所影响的行数为 7 行)project    num         差缺数         
    ---------- ----------- ----------- 
    c          20          19
    a          30          14
    b          50          23
    d          80          80(所影响的行数为 4 行)
    */