有表
商品       收入        发出      结存
月初数                            10
a            5           0          
b            0           2如何用update 语句更新结存数,结存数为上一行的结存+本行的收入-本行的发出
如上表中a的结存为15,b的结存为13
要求:不用游标,尽量不用循环,只用一句话

解决方案 »

  1.   

    declare @结存 int
    update tb
      set @结存=case when @结存 is null then 结存 else @结存+收入-发出 end,
          结存=@结存
      

  2.   

    --楼上的巧妙啊!!先赞一个多
    弄一个ID自增的字段
    update tb
    set 结存= (select 结存 from tb where id =(select max(id) from tb where id <T.id)))
                +收入
                -发出
    from tb T--//Oracle里面用分析函数一下就搞定
      

  3.   

    update tb
    set 结存= isnull((select 结存 from tb where id =(select max(id) from tb where id <T.id))),0)
                +收入
                -发出
    from tb T
      

  4.   

    if object_id('pubs..tb') is not null
       drop table tb
    gocreate table tb
    (
    商品 varchar(10),
    收入 int,
    发出 int,
    结存 int
    )insert into tb(商品,收入,发出,结存) values('月初数',null,null,10)
    insert into tb(商品,收入,发出,结存) values('a',5,0,0)
    insert into tb(商品,收入,发出,结存) values('b',0,2,0)update tb
    set 结存=(select isnull(sum(收入-发出),0) 
    from tb tt 
    where tt.商品<=tb.商品 and tb.商品<>'月初数')+(select 结存 from tb where 商品='月初数') select * from tb
    drop table tb商品       收入        发出        结存          
    ---------- ----------- ----------- ----------- 
    月初数     NULL        NULL        10
    a          5           0           15
    b          0           2           13(所影响的行数为 3 行)