How to get cumulative sum

前端 未结 16 2352
遇见更好的自我
遇见更好的自我 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:23

    Select *, (Select SUM(SOMENUMT) From @t S Where S.id <= M.id) From @t M

    0 讨论(0)
  • 2020-11-22 04:24

    For Ex: IF you have a table with two columns one is ID and second is number and wants to find out the cumulative sum.

    SELECT ID,Number,SUM(Number)OVER(ORDER BY ID) FROM T
    
    0 讨论(0)
  • 2020-11-22 04:25

    Try this:

    CREATE TABLE #t(
     [name] varchar NULL,
     [val] [int] NULL,
     [ID] [int] NULL
    ) ON [PRIMARY]
    
    insert into #t (id,name,val) values
     (1,'A',10), (2,'B',20), (3,'C',30)
    
    select t1.id, t1.val, SUM(t2.val) as cumSum
     from #t t1 inner join #t t2 on t1.id >= t2.id
     group by t1.id, t1.val order by t1.id
    
    0 讨论(0)
  • 2020-11-22 04:26

    For SQL Server 2012 onwards it could be easy:

    SELECT id, SomeNumt, sum(SomeNumt) OVER (ORDER BY id) as CumSrome FROM @t
    

    because ORDER BY clause for SUM by default means RANGE UNBOUNDED PRECEDING AND CURRENT ROW for window frame ("General Remarks" at https://msdn.microsoft.com/en-us/library/ms189461.aspx)

    0 讨论(0)
提交回复
热议问题