The latest version of SQL Server (2012) permits the following.

SELECT 
    RowID, 
    Col1,
    SUM(Col1) OVER(ORDER BY RowId ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS Col2
FROM tablehh
ORDER BY RowId

or

SELECT 
    GroupID, 
    RowID, 
    Col1,
    SUM(Col1) OVER(PARTITION BY GroupID ORDER BY RowId ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS Col2
FROM tablehh
ORDER BY RowId

This is even faster. Partitioned version completes in 34 seconds over 5 million rows for me.

Thanks to Peso, who commented on the SQL Team thread referred to in another answer.

Answer from Gareth Adamson on Stack Overflow
🌐
Reddit
reddit.com › r/sql › cumulative sum or running sum
r/SQL on Reddit: Cumulative sum or running sum
March 10, 2023 -

Hello!

I am trying to write a SQL query using a combination of CTE and windows function to calculate a cumulative sum of the count of product.

My apologize as I'm using my mobile but here is an example of the dataset

Productcode RATE1 RATE1 RATE3 RATE1 RATE3 RATE2

The original table has a lot of columns but I'm only interested into 1. It also has customer id but a customer can only have 1 product. There is also date row but I'm not interested in the date

I wrote the below with the idea of taking a column out of many from the original dataset, group the product code and get individual count of each rate and finally add a column running a cumulative sum

WITH testtable AS (Select Productcode ,Count(*) as Freq From table group by 1) Select Productcode ,Sum(Freq) over (partition by productcode) as cumul From testtable

The output is essentially a duplicate of the column Freq as opposed to the cumulative Freq as I hoped.

I also appreciate that there is certainly an easier way of getting this done but I still would like to know why it is not working?

Thanks for your inputs!

Edit: moved 'AS' to the correct position Edit 2: sample dataset and further clarifications Edit 3: solved SUM(COLUMN) OVER (ORDER BY productid)

Discussions

sql server - Cumulative sum in SQL using window function - Stack Overflow
QTY STOCK RNK ID KEY CUM SUM 40 35 1 1 35 20 35 2 1 0 15 35 3 1 0 58 35 4 1 0 18 35 5 1 0 40 35 1 2 35 20 35 2 2 0 15 35 3 2 0 CUM SUM should be MIN(QTY, STOCK-SUM(all rows in cumsum before the cur... More on stackoverflow.com
🌐 stackoverflow.com
Cumulative sum or running sum
I think for it to be a running Sum you need ORDER BY in your parenthesis. SUM(COLUMN) OVER (ORDER BY productid) More on reddit.com
🌐 r/SQL
11
5
March 10, 2023
Replicating ROW BETWEEN INTERVAL sliding window frame in Snowflake
First off, thank you for the high quality question. In Snowflake, to do a sliding window cumulative sum you need to either: Perform a self-join Construct a "spine" that's populated with every account_id/date possible in the dataset I find that the former is good enough for small datasets. That would look like: SELECT orig.account_id, orig.transaction_id, orig.transaction_date, orig.amount, SUM(rolling.amount) AS rolling_24mo_sum FROM transactions as orig JOIN transactions as rolling ON orig.account_id = rolling.account_id AND rolling.transaction_date BETWEEN orig.transaction_date - INTERVAL '24 MONTHS' AND orig.transaction_date GROUP BY ALL u/fhoffa has an example on Stack Overflow here . More on reddit.com
🌐 r/snowflake
5
4
December 14, 2023
SQL Running total, reset when a column is a certain value?
;with ShiftStartSeq as ( select Login ,ShiftSeq = row_number() over (order by Login) from ScreenShotTable where LogoutReason = 'SHIFT START' ) ,ShiftEndSeq as ( select Logout ,ShiftSeq = row_number() over (order by Logout) from ScreenShotTable where LogoutReason = 'SHIFT END' ) ,FullShiftSeq as ( select ss.ShiftSeq, ss.Login, se.Logout from ShiftStartSeq ss join ShiftEndSeq se on ss.ShiftSeq = se.ShiftSeq ) ,ScreenShotTableGrouped as ( select sst.*, fs.ShiftSeq from ScreenShotTable sst join FullShiftSeq fs on sst.Login >= fs.Login and sst.Logout <= fs.Logout ) ,WithRunningTotal as ( select * ,RunningTotal = sum(loginDuration) over (partition by ShiftSeq order by Login) from ScreenShotTableGrouped ) select * from WithRunningTotal More on reddit.com
🌐 r/SQLServer
12
8
June 11, 2021
🌐
Dawiso
dawiso.com › home › glossary › sql sum() over - guide to running totals and cumulative sums
SQL SUM() OVER - Guide to Running Totals and Cumulative Sums | Dawiso
March 20, 2026 - SUM() OVER calculates running totals and cumulative sums without collapsing rows. It is a window function — it adds a computed column to each row based on a sliding window of related rows.
🌐
Interview Query
interviewquery.com › p › sql-cumulative-sum-guide
SQL Cumulative SUM: Window Functions, Rolling Totals & Best Practices
March 17, 2026 - ... SELECT customer_id, order_date, amount, SUM(amount) OVER ( PARTITION BY customer_id ORDER BY order_date ) AS cumulative_by_customer FROM orders; Here, the running total resets for each customer.
🌐
Oracle
blogs.oracle.com › sql › cumulative-running-total-of-previous-rows-with-sql
How to get the cumulative running total of previous rows with SQL
March 2, 2023 - To calculate the running total for a column you can use analytic functions, aka window functions. The basic syntax is: sum ( col ) over ( order by sort_col rows unbounded preceding ) So to get the cumulative sum of employee salaries, in the ...
🌐
StrataScratch
stratascratch.com › blog › computing-cumulative-sum-in-sql-made-easy
Computing Cumulative Sum in SQL Made Easy - StrataScratch
May 8, 2025 - Note: Depending on your task, you might also need to use PARTITION BY, another interesting clause in window functions. It is used when you want to partition a window into smaller groups. For example, if you had a table showing consumption in Europe and several of its cities, PARTITION BY would allow you to calculate the cumulative sum for each city, not only for the whole continent. We have a nice explanation of PARTITION BY in our SQL cheat sheet.
🌐
LinkedIn
linkedin.com › pulse › using-window-functions-get-cumulative-sum-sql-josé-erildo-1f
Using Window Functions to Get Cumulative Sum in SQL
September 29, 2023 - select date, amount, sum(amount) over(order by date ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW ) as cumulativesum from table;
Find elsewhere
🌐
Five
five.co › blog › sql-cumulative-sum
SQL Cumulative Sum: A Practical Guide | Five
May 4, 2026 - The SUM() OVER () syntax we used above is called a window function. Window functions are the secret sauce that makes cumulative sums in SQL possible.
🌐
Microsoft Learn
learn.microsoft.com › en-us › sql › t-sql › functions › sum-transact-sql
SUM (Transact-SQL) - SQL Server | Microsoft Learn
July 20, 2026 - Applies to: SQL Server Azure SQL ... Microsoft Fabric SQL database in Microsoft Fabric · Returns the sum of all the values, or only the DISTINCT values, in the expression....
🌐
Medium
medium.com › geekculture › sql-interview-question6-finding-cumulative-sum-use-case-of-sum-over-aggregate-window-dfe379d39f63
SQL Interview Question6: Finding Cumulative Sum — Use Case of SUM() OVER () Aggregate Window Function | by Deeksha Singh | Geek Culture | Medium
December 1, 2022 - But the problem statement is to find the cumulative sum of salaries not total salaries. So instead of aggregating all the salaries in one row, we want running total. Here using sum() function with over() clause as window function will do our job i.e., it won’t aggregate the output in one row.
🌐
W3Schools
w3schools.com › sql › sql_aggregate_functions.asp
SQL Aggregate Functions
String Functions: ASCII CHAR_LENGTH CHARACTER_LENGTH CONCAT CONCAT_WS FIELD FIND_IN_SET FORMAT INSERT INSTR LCASE LEFT LENGTH LOCATE LOWER LPAD LTRIM MID POSITION REPEAT REPLACE REVERSE RIGHT RPAD RTRIM SPACE STRCMP SUBSTR SUBSTRING SUBSTRING_INDEX TRIM UCASE UPPER Numeric Functions: ABS ACOS ASIN ATAN ATAN2 AVG CEIL CEILING COS COT COUNT DEGREES DIV EXP FLOOR GREATEST LEAST LN LOG LOG10 LOG2 MAX MIN MOD PI POW POWER RADIANS RAND ROUND SIGN SIN SQRT SUM TAN TRUNCATE Date Functions: ADDDATE ADDTIME CURDATE CURRENT_DATE CURRENT_TIME CURRENT_TIMESTAMP CURTIME DATE DATEDIFF DATE_ADD DATE_FORMAT DA
🌐
DataCamp
datacamp.com › tutorial › sql-sum
SQL SUM() Function Explained | DataCamp
August 15, 2024 - Example table output using SQL SUM() function to calculate cumulative sums. Image by Author. I recommend taking DataCamp’s Data Manipulation in SQL course, which details the use of window functions in aggregation for techniques such as calculating running totals.
🌐
dplyr
dplyr.tidyverse.org › articles › window-functions.html
Window functions • dplyr
Base R provides cumulative sum (cumsum()), cumulative min (cummin()), and cumulative max (cummax()). (It also provides cumprod() but that is rarely useful). Other common accumulating functions are cumany() and cumall(), cumulative versions of ...
🌐
Baeldung
baeldung.com › home › sql queries › calculating running totals in sql
Calculating Running Totals in SQL Baeldung on SQL
October 12, 2024 - To calculate the running total ... OVER (ORDER BY id) AS RunningTotal FROM Exam; ... The SUM(scores) function calculates the cumulative sum of the scores column for each row....
🌐
PopSQL
popsql.com › learn-sql › mysql › how-to-calculate-cumulative-sum-running-total-in-mysql
How to Calculate Cumulative Sum-Running Total in MySQL - PopSQL
SELECT t.day, t.rental_count, @running_total:=@running_total + t.rental_count AS cumulative_sum FROM ( SELECT date(rental_date) as day, count(rental_id) as rental_count FROM rental GROUP BY day ) t JOIN (SELECT @running_total:=0) r ORDER BY t.day; day | rental_count | cumulative_sum -----------+--------------+---------------- 2005-05-24 | 8 | 8 2005-05-25 | 137 | 145 2005-05-26 | 174 | 319 2005-05-27 | 166 | 485 2005-05-28 | 196 | 681 · For MySQL 8 you can use a windowed SUM() and also a MySQL common table expression (CTE) instead of a subquery to make it more readable, the result is the same:
🌐
Milvus
milvus.io › home › ai reference › how do you calculate running totals in sql?
How do you calculate running totals in SQL?
For example, if you have a sales table with order_date and amount columns, the query SELECT order_date, amount, SUM(amount) OVER (ORDER BY order_date) AS running_total FROM sales; calculates the cumulative sales amount over time.
🌐
GeeksforGeeks
geeksforgeeks.org › postgresql › compute-a-running-total-in-postgresql
Compute a Running Total in Postgresql - GeeksforGeeks
July 23, 2025 - The running_total column will contain the cumulative sum of the amount column up to that particular row, ordered by the date. ... Another approach is to use recursive common table expressions (CTEs). This method is useful when dealing with complex calculations or in scenarios where window functions may not be applicable.
🌐
Flexera
flexera.com › blog › finops › snowflake-cumulative-sum
HOW TO: Calculate cumulative sum in Snowflake (2026)
August 11, 2026 - Now we’re ready to calculate Snowflake cumulative sums. ... To calculate the total sum for each row across the entire dataset, use the SUM() function with the OVER() clause. SELECT order_id, order_date, product_category, order_amount, ...