Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cumulative Additions in SQL Server 2008

I am trying to add the previous row value to the current row and keep this adding until I reach the total.

I have tried the below query and I have set row number to the rows as per my needs, the additions should take place in the same manner.

select * 
from #Finalle 
order by rownum ;

Output:

Type                    Count_DB    Rownum
------------------------------------------
Within 30 days          399480       1
Within 60 days          30536        2
Within 90 days          10432        3
Within 120 days         11777        4
Greater than 120 days   13091        5
Blank                   29297        6
Total                   494613       7

When I try the below query, it works fine until the 6th row, but fails for the last row:

select 
    f1.[type],
    (select 
         Sum(f.[Count of ED_DB_category]) as [Cummumative] 
     from 
         #Finalle f 
     where 
         f1.rownum >= f.rownum) 
from 
    #Finalle f1
order by 
    rownum

Output:

Type                   No column name
--------------------------------------
Within 30 days         399480
Within 60 days         430016
Within 90 days         440448
Within 120 days        452225
Greater than 120 days  465316
Blank                  494613 <---Add only until here
Total                  989226

Here the total should return the same value as in the first table.

How do I achieve this?

like image 436
Ruchi Avatar asked May 17 '26 04:05

Ruchi


1 Answers

Try this:

select f1.[type],
       CASE
          WHEN type = 'Total' THEN f1.[Count_DB]
          ELSE SUM(f1.[Count_DB]) OVER (ORDER BY rownum) 
       END      
from #Finalle f1
order by rownum
like image 96
Giorgos Betsos Avatar answered May 18 '26 17:05

Giorgos Betsos



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!