例如这个表id   num
1     1
2     0
3     0
4     0
5     0
6     0现在的问题是先要把id1的num值平方,然后加上id2,得出值填入id2的num中,具体就是下表id   num
1     1
2     3
3     12
4     148
。这个语句应该怎么写啊,虚心求教,我想过用游标,可惜太慢了

解决方案 »

  1.   

    也就是每一行取上一行的num值,平方后加上本行的id值,作为本行的num值
      

  2.   

    declare @t table(id int,num int)
    insert into @t select 1,1
    insert into @t select 2,0
    insert into @t select 3,0
    insert into @t select 4,0
    insert into @t select 5,0
    insert into @t select 6,0declare @sum int
    set @sum=0update @t set @sum=@sum*@sum+num,num=@sumselect * from @t
      

  3.   

    update tablename set num = (select num from tablename where id = id -1)*(select num from tablename where id = id -1)+(select id from where id = id )
      

  4.   

    如果稍微复杂些呢,比如下表
    index    id     num
      a       1      3
      a       2      0
      a       3      0
      a       4      0
      b       1      4
      b       2      0
      b       3      0
      b       4      0按照要求的话是按照index分组更新,这个语句又该如何,虚心求教
      

  5.   

    游标.因为你现在就是没有数据在num字段里(除了第一个),每一个num的填充都需要上一个id的num先算出来.所以只能用游标依次处理.如果是一次同时处理num字段的话倒是可以用关联来做.但目前的业务逻辑用关联是不对的.
      

  6.   

    libin_ftsafe(子陌红尘:当libin告别ftsafe)的方法我试了,可行,现在正在研究有分组的做法,不知道应该怎么弄,大家也帮忙研究下,要是有for each 就好了 ^_^
      

  7.   

    这样试试:
    declare @t table([index] varchar(10),id int,num int)
    insert @t
    select 'a',1,3 union all
    select 'a',2,0 union all
    select 'a',3,0 union all
    select 'a',4,0 union all
    select 'b',1,4 union all
    select 'b',2,0 union all
    select 'b',3,0 union all
    select 'b',4,0declare @sum int
    set @sum=0UPDATE @t set @sum=
    case 
    when not exists(select 1 from @t where [index] = a.[index] and id < a.id)
    then num      /*当是每组的第一行时初始化@num*/
    else @sum*@sum+id 
    end,
    num=@sum
    FROM @t aselect * from @t