How to get cumulative sum

前端 未结 16 2357
遇见更好的自我
遇见更好的自我 2020-11-22 03:32
declare  @t table
    (
        id int,
        SomeNumt int
    )

insert into @t
select 1,10
union
select 2,12
union
select 3,3
union
select 4,15
union
select 5,23         


        
16条回答
  •  情歌与酒
    2020-11-22 04:08

    A CTE version, just for fun:

    ;
    WITH  abcd
            AS ( SELECT id
                       ,SomeNumt
                       ,SomeNumt AS MySum
                 FROM   @t
                 WHERE  id = 1
                 UNION ALL
                 SELECT t.id
                       ,t.SomeNumt
                       ,t.SomeNumt + a.MySum AS MySum
                 FROM   @t AS t
                        JOIN abcd AS a ON a.id = t.id - 1
               )
      SELECT  *  FROM    abcd
    OPTION  ( MAXRECURSION 1000 ) -- limit recursion here, or 0 for no limit.
    

    Returns:

    id          SomeNumt    MySum
    ----------- ----------- -----------
    1           10          10
    2           12          22
    3           3           25
    4           15          40
    5           23          63
    

提交回复
热议问题