create table t1(id int,num int)
insert t1
select 1,1000 union select 2,100
union select 3,200 union select 4,300
union select 5,400 union select 6,800go
create function f_1(@jine int)
returns @tb table(id int,num int)
as
begin
declare @id int,@num int,@total int
declare cur cursor for select id,num from t1 order by num
open cur
set @total=0
fetch next from cur into @id,@num
while @@fetch_status=0
begin
if @total+@num<=@jine
begin
insert @tb select @id,@num
set @total=@total+@num
end
fetch next from cur into @id,@num
end
return
end
go
select * from dbo.f_1(1000)
drop table t1
drop function f_1
/*
id          num         
----------- ----------- 
2           100
3           200
4           300
5           400(所影响的行数为 4 行)*/

解决方案 »

  1.   

    就是说这句 select id,num from t1 order by num从小往大排的话,不能尽可能多的满足供给金额!
      

  2.   

    楼主,wgsasd311(自强不息) 的是一重循环,从小到大的加,
    你试试从大到小的去减,外面再套一层循环(判断从那开始减),就能把所有方案查出来了
      

  3.   

    就是说这句 select id,num from t1 order by num从小往大排的话,不能尽可能多的满足供给金额!
    -----------请问楼主,在1500时:如果一组是有三个相加达到1400,别一组是4个相加达到1200,那么选哪一组呢?
      

  4.   

    bugchen888(臭虫):
    当然是1更好。因为他满足了更多的需求。
    wgsasd311(自强不息) 
    这个问题我还没想过!但是你的函数,在计算1500这个值时确实存在问题。100
    200
    300
    400
    800
    1000
    这样排时,1000计算没问题,但是1500时,和1000的一样,
    逻辑上倒没有问题,但是不是最好的解决方案啊
      

  5.   

    就是说这句 select id,num from t1 order by num从小往大排的话,不能尽可能多的满足供给金额!
    -----------请问楼主,在1500时:如果一组是有三个相加达到1400,别一组是4个相加达到1200,那么选哪一组呢?对呀,在满足的count(num)和sum(num)之间应该如何取舍?楼主问的应该是数学上的最优化问题。