简体   繁体   中英

SQL query to calculate sum of row with previous row

This is my table

date     count of subscription per date
----      ----------------------------
21-03-2016      10
22-03-2016      30
23-03-2016      40 

Please need your help, I need to get the result like below table, summation second row with first row, same thing for another rows:

date     count of subscription per date
----      ----------------------------
21-03-2016      10
22-03-2016      40
23-03-2016      80 
Select sum(col1) over(order by date rows between unbounded preceding and current row) cnt from mytable;

You can do a cumulative sum using the ANSI standard analytic SUM() function:

select date, sum(numsubs) over (order by date) as cume_numsubs
from t;
SELECT t.date, (
    SELECT SUM(numsubs) 
    FROM mytable t2 
    WHERE t2.date <= t.date
) AS cnt
FROM mytable t

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM