表a
id amount 
1   3
2   15
3   20
4   28给一个数字@b = 30
要查出b在对amount求和的哪条记录的范围内比如 1 + 15 + 20 > 30并且 1 + 15 < 30
那么@b就应该在3这个id范围内不知道我说清楚意思没有谢谢各位

解决方案 »

  1.   

    declare @t table(id int,amount int)
    insert into @t select 1,3
    insert into @t select 2,15
    insert into @t select 3,20
    insert into @t select 4,28declare @a int,@b int,@id int
    set @a=0
    set @b=30select
        @id=case 
               when @b>@a and @b<=@a+amount then id 
               else @id
             end,
        @a =@a+amount
    from
        @tselect @id as id/*
    id          
    ----------- 
    3
    */
      

  2.   

    libin_ftsafe(子陌红尘:当libin告别ftsafe) 谢谢确实可以能讲讲道理吗?@id=case
    when @b>@a and @b<=@a+amount then id
    else @id
    end,这里当@b<=@a or @b>@a+amount
    的时候返回@id,为什么数据库会一直往后面的记录读呢?
      

  3.   

    该条SQL语句回遍历全表,但是一旦获得满足条件的记录号之后,记录号不再改变,直至遍历完成输出满足条件的记录。在该句SQL中,无法实现条件满足则Return。
      

  4.   

    declare @t table(id int,amount int)
    insert into @t select 1,3
    insert into @t select 2,15
    insert into @t select 3,20
    insert into @t select 4,28select a.id from @t a
    where (select sum(amount) from @t where id<a.id)<30 and (select sum(amount) from @t where id<=a.id)>=30