新增资金   累积资金
      a1        b1
      a2        b2
      a3        b3
关系:b1=a1+0;
      b2=b1+a2;
      b3=b2+a3;
请问下在数据库里面怎么处理这种情况阿
不知累积资金列如何计算?

解决方案 »

  1.   

    --需要唯一id以替代游标,日期也可以declare @test table
    (
    id int,
    A int,
    B int
    )
    insert into @test (id,A)
    select 1,100 union all
    select 2,90 union all
    select 3,50update t 
    set B=(select isnull(sum(A),0) from @test where id<=t.id)+(select isnull(sum(B),0) from @test where id<t.id)
    from @test tselect * from @test
    /*
    id          A           B           
    ----------- ----------- ----------- 
    1           100         100
    2           90          190
    3           50          240
    */
      

  2.   

    --其實 B=sum(A) where id<=t.id就可以了
    --借用下 夜游神 大哥的測試數據
    --set後面的那個+,後面的sum(B)好像衡=0declare @test table
    (
    id int,
    A int,
    B int
    )
    insert into @test (id,A)
    select 1,100 union all
    select 2,90 union all
    select 3,50update t 
    set B=(select isnull(sum(A),0)  from @test  where id<=t.id)
    from @test tselect * from @test
    -------------
    id          A           B           
    ----------- ----------- ----------- 
    1           100         100
    2           90          190
    3           50          240
      

  3.   

    B的結果應該是=sum(A) where id<=t.id
     
    或者=(A where id=t.id)+(B where id=t.id-1)
      

  4.   

    现在我有现成的表ProjInvest
    但是我如何赋值给@test呢
    或者有针对现成表的方法吗?
      

  5.   

    你原表必须有一个可以区分先后顺序的字段(MSSQL2000没有行号的概念)否则你凭什么告诉SQL加和应该到何处为止?如果没有,自行添加一个此外@test只是测试用表变量,和你的表的不发生关系
      

  6.   

    id     nd(年度)     A           B           
    ----------- ----------- ----------- 
    1    2004    100         100
    2    2004     90          190
    3    2004     50          240
    合计 2004     240
    4    2005    100         100
    5    2005     90          190
    6    2005     50          240
    合计 2005     240
    对于
    id     nd(年度)     A           B           
    ----------- ----------- ----------- 
    1    2004    100         100
    2    2004     90          190
    3    2004     50          240
    我在大家的帮助下能够实现了 谢谢
    但是现在我是以年度来分组统计的
    这时where id<=t.id
    就会失效了,因为2004年的值可能就会加入2005年上去
    所以现在主要问题是怎么来确定ID是2004年的还是2005年的 
    ??
      

  7.   

    参考下面这样set B=(select isnull(sum(A),0)  from @test  where id<=t.id and year=t.year)
    from @test t
      

  8.   

    非常感谢LouisXIV(夜游神) 
    不过我还想问一下@test与t的关系
    为什么我把@test换成具体表之后
    B就不会动态变化了 就一直为最终的统计结果了
    不是说@test只是测试用表变量吗
    但是不用好像就不行了呀?
      

  9.   

    t只是一个别名而已,用于区别子查询内的@test