t1结构
jh      xjxh    tgmc    tggc xs
BK  0 a 5    5.00
BK  1 a 5    5.00
BK  2 a 5    5.00
BK  3 a  5    5.00
BK  5 a 5    5.00UPDATE t1 SET XS=
(SELECT XS FROM
(select JH,XJXH,TGMC,
(    
select SUM(isnull(TGGC,0)) from t1 b where B.jh=t1.jh and t1.xjxh>=B.xjxh AND B.XJXH>0 AND t1.TGMC=B.TGMC
)
+
(SELECT XS FROM t1 C WHERE t1.JH=C.JH AND C.XJXH=0 AND C.TGMC=t1.TGMC
)  AS XS from t1 
) AS T_XS
 WHERE t1.JH=T_XS.JH AND t1.XJXH=T_XS.XJXH AND t1.TGMC=T_XS.TGMC
)
WHERE XJXH>0
运行结果如下
jh      xjxh    tgmc    xs
BK  0 a 5.00
BK  1 a 10.00
BK  2 a 15.00
BK  3 a  20.00
BK  5 a 25.00我想问下 这里update是如何更新的?请详细说下过程

解决方案 »

  1.   

    我只是想知道这句update是如何执行的
      

  2.   

    create table tb(jh varchar(10), xjxh int, tgmc varchar(10), tggc int , xs decimal(18,2))
    insert into tb values('BK', 0, 'a', 5 , 5.00 )
    insert into tb values('BK', 1, 'a', 5 , 5.00 )
    insert into tb values('BK', 2, 'a', 5 , 5.00 )
    insert into tb values('BK', 3, 'a', 5 , 5.00 )
    insert into tb values('BK', 5, 'a', 5 , 5.00 )
    go
    --查询
    select jh,xjxh,tgmc,xs = (select sum(xs) from tb where jh = t.jh and xjxh <= t.xjxh) from tb t
    /*
    jh         xjxh        tgmc       xs
    ---------- ----------- ---------- ---------------------------------------
    BK         0           a          5.00
    BK         1           a          10.00
    BK         2           a          15.00
    BK         3           a          20.00
    BK         5           a          25.00(5 行受影响)
    */
    --更改
    update tb set xs = (select sum(xs) from tb where jh = t.jh and xjxh <= t.xjxh) from tb t
    select * from tb
    /*
    jh         xjxh        tgmc       tggc        xs
    ---------- ----------- ---------- ----------- ---------------------------------------
    BK         0           a          5           5.00
    BK         1           a          5           10.00
    BK         2           a          5           15.00
    BK         3           a          5           20.00
    BK         5           a          5           25.00(5 行受影响)
    */drop table tb
      

  3.   

    如果你还需要tgmc,tggc这两个字段的条件,自己加上即可.
      

  4.   

    select sum(xs) from tb where jh = t.jh and xjxh <= t.xjxh
    这句产生的数据是什么样的?
    是计算一次sum,更新一次?
    还是全部计算出来,再更新?
      

  5.   

    根据当前行,找符合记录的SUM(xs)
      

  6.   

    那就是 计算一次sum,更新一次啦
      

  7.   

    LZ语句,应该是统计tggc列和值,更新到xs中,若tggc不全相等,则老乌龟答案就不对了
    declare  @tb table(jh varchar(10), xjxh int, tgmc varchar(10), tggc int , xs decimal(18,2))
    insert into @tb values('BK', 0, 'a', 5 , 5.00 )
    insert into @tb values('BK', 1, 'a', 6 , 5.00 )
    insert into @tb values('BK', 2, 'a', 8 , 5.00 )
    insert into @tb values('BK', 3, 'a', 10 , 5.00 )
    insert into @tb values('BK', 5, 'a', 12 , 5.00 )
    --更新
    update @tb set xs=(select sum(tggc) from @tb where jh=t.jh and xjxh<=t.xjxh)  from @tb t--查询
    select * From @tb/*BK 0 a 5 5.00
    Bk 1 a 6 11.00
    BK 2 a 8 19.00
    BK 3 a 10 29.00
    Bk 5 a 12 41.00 */