update tablea
set t4 = t4 - (select sum(t3)
                from tablea
                where a.t2 = t2 and t1<= a.tid )
from tablea a

解决方案 »

  1.   

    create table t(t1  int,t2 char(2),t3 int,t4 int)
    insert t 
    select 1,'A1',20,100 union all
    select 2,'A1',20,100 union all
    select 3,'A2',10,50 union all
    select 4,'A2',20,50 union all
    select 5,'A1',10,100 union all
    select 6,'A2',5,50
    go
    select * from t
    update t
    set t4 = t4 - (select sum(t3)
                    from t
                    where a.t2 = t2 and t1<= a.t1 )
    from t a
    select * from tdrop table t/*
    t1          t2   t3          t4          
    ----------- ---- ----------- ----------- 
    1           A1   20          100
    2           A1   20          100
    3           A2   10          50
    4           A2   20          50
    5           A1   10          100
    6           A2   5           50(所影响的行数为 6 行)
    (所影响的行数为 6 行)t1          t2   t3          t4          
    ----------- ---- ----------- ----------- 
    1           A1   20          80
    2           A1   20          60
    3           A2   10          40
    4           A2   20          20
    5           A1   10          50
    6           A2   5           15(所影响的行数为 6 行)
    */
      

  2.   

    update table set t4=t4 - (select sum(t3) from table where t2=a.t2 and t1<=a.t1)
    from table a
      

  3.   

    declare @t table(t1 int,t2 varchar(10),t3 int,t4 int)
    insert into @t select 1,'A1',20,100
    insert into @t select 2,'A1',20,100
    insert into @t select 3,'A2',10,50
    insert into @t select 4,'A2',20,50
    insert into @t select 5,'A1',10,100
    insert into @t select 6,'A2',5 ,50update a
    set
        t4=a.t4-(select sum(t3) from @t where t2=a.t2 and t1<=a.t1)  
    from 
        @t aselect * from @t/*
    t1          t2         t3          t4          
    ----------- ---------- ----------- ----------- 
    1           A1         20          80
    2           A1         20          60
    3           A2         10          40
    4           A2         20          20
    5           A1         10          50
    6           A2         5           15
    */