表table中有一列叫money,存放现金数据
现在sum(money)= 5750000.00
现在想删除部分数据,要求删除后sum(money)=3578000.00,或者尽可能的接近3578000.00(必须小于3578000.00),怎样实现?

解决方案 »

  1.   

    有难度,分太少,懒得想.
    就算在SQL中用算法实现,效率也太差.
      

  2.   

    用存储过程做
    先将money排序,然后循环,从最小删起,每删一行,就sum一次,直到小于你要求的值为止
      

  3.   


    --这个有个例子,添加一个辅助列,summ为辅助列
    create table #1(id int,value int)insert into #1(id,value)
    select 1,20
    union all 
    select 2,50
    union all
    select 3,20
    union all 
    select 4,5
    union all
    select 5,10--金额排序写入另一个临时表
    select id,value,summ=0 into #2
    from #1 order by valuedeclare @sum int
    set @sum=0update #2 set @sum=value+@sum,summ=@sum---这里假定限额为80
    delete from #2 where summ>80select * from #2
      

  4.   

    楼上的是
    select a.*,(select sum(b.num) from tb b where b.num<a.num) from tb a order by num
    的思路.我想复杂了,失策.
      

  5.   

    ReViSion(和尚) ( ) 信誉:100  2006-08-11 23:49:00  得分: 0  
     
     
       哈哈,不好意思,看错啦尽可能的接近3578000.00(必须小于3578000.00),怎样实现?
    -----------------------------------------------------
    如果一定要求这个极限值,数据量大的话几乎做不到
      
     
    你的这种思路,理论上是可以的,因为是从最小值开始计算的.不过正如你所说,数据量太大的话查询成问题.
      

  6.   

    对,是的.
    tb
    id value
    1 3
    2 1
    3 4
    4 1
    5 9
    6 20比如要求某个值为 17
    按value排是
    1,1,3,4,9,20
    取到第9时已经超过17了,只能取前四,和为 9
    而实际上这个最接近的组合应该是 9,4,3,1
    是比较复杂.hehe
      

  7.   

    --生成测试数据
    create table #t(id int,value int)
    insert into #t(id,value)
    select 1,20
    union all 
    select 2,35
    union all
    select 3,10
    union all 
    select 4,20
    union all
    select 5,4
    union all
    select 6,11declare @t table (id int ,value int) --定义表变量记录要保存的数据,其实只存个ID就可以了
    declare @sum int,@id int,@value int,@total int
    select @sum=0,@total=80,@value=0  --用@total保存设定要达到的值,这里为80--不喜欢用循环,不得已而用之
    while @sum<@total
    begin
    select @id=id,@value=value from #t a where not exists(select 1 from @t b where b.id=a.id) and value+@sum<=@total order by value,id
    set @sum=@sum+@value
    insert @t select @id,@value
    end
    delete from #t where id not in(select id from @t)  --删除不需要保留的记录
    select * from #t
    drop table #t
    /*结果
    1 20
    2 35
    4 20
    5 4
    */