表1ID  区间  金额
1   刘    100
2   我    300
3   王    -100
4   宋    800
5   李    -200
求累计金额
得结果 表2
ID  区间  金额 累计
1   刘    100 100
2   我    300  400
3   王    -100 300
4   宋    800  1100
5   李    -200 900谢谢

解决方案 »

  1.   


    select
    a.ID,
    a.区间,
    金额 = (
    select sum(金额)
    from 表1
    where ID <= a.ID
    )
    from 表1 a
      

  2.   

    declare @t table(ID int,  区间 varchar(10), 金额 int) 
    insert @t select 1 , '刘',    100 union all select 
    2,  '我',    300 union all select 
    3,  '王',    -100 union all select 
    4,  '宋',    800  union all select 
    5,  '李',    -200 
    select id, 区间,金额,累计=(select sum(金额) from @t where id<=t.id)
    from @t t
    /*
    (所影响的行数为 5 行)id          区间         金额          累计          
    ----------- ---------- ----------- ----------- 
    1           刘          100         100
    2           我          300         400
    3           王          -100        300
    4           宋          800         1100
    5           李          -200        900*/