如何统计累计相加落差问题名称  数量
1      1
2      3
3      5
4      4
5      -1
6      -7
7      -6
8      3
9      2
10     -1
11     -2
..................
得结果名称  数量 落差
1      1    1
2      3    4
3      5    9
4      4    13
5      -1    -1------因为累计数字要回落了,所有从新开始计数
6      -7    -8    
7      -6    -14
8      3    3------因为累计数字要回落了,所有从新开始计数
9      2    5
10     -1    -1------因为累计数字要回落了,所有从新开始计数
11     -2    -3

解决方案 »

  1.   

    declare @t table(a int,b int)
    insert into @t select 1 , 1 
    insert into @t select 2 , 3 
    insert into @t select 3 , 5 
    insert into @t select 4 , 4 
    insert into @t select 5 ,-1 
    insert into @t select 6 ,-7 
    insert into @t select 7 ,-6 
    insert into @t select 8 , 3 
    insert into @t select 9 , 2 
    insert into @t select 10,-1 
    insert into @t select 11,-2select
        m.a,sum(n.b) as b
    from 
        @t m,@t n 
    where 
        m.a>=n.a 
        and                      
        n.a>isnull((select top 1 a from @t where a<m.a and ((b>0 and m.b<0) or (b<0 and m.b>0)) order by a desc),0)
    group by
        m.a/*
    a           b           
    ----------- ----------- 
    1           1
    2           4
    3           9
    4           13
    5           -1
    6           -8
    7           -14
    8           3
    9           5
    10          -1
    11          -3
    */
      

  2.   

    SQL codedeclare @t table(a int,b int) 
    insert into @t select 1 , 1 
    insert into @t select 2 , 3 
    insert into @t select 3 , 5 
    insert into @t select 4 , 4 
    insert into @t select 5 ,-1 
    insert into @t select 6 ,-7 
    insert into @t select 7 ,-6 
    insert into @t select 8 , 3 
    insert into @t select 9 , 2 
    insert into @t select 10,-1 
    insert into @t select 11,-2 select 
        m.a,sum(n.b) as …