Coginiti menu Coginiti menu

Calculate Cumulative Sum (Running Total)

You can use the window function SUM with the OVER clause to calculate a cumulative sum or running total in SQL.

SELECT column1, column2, SUM(column3) OVER (ORDER BY column1) as cumulative_sum 
FROM your_table; 

This will create a new column called cumulative_sum that shows the running total of values in column3 for each row, ordered by column1. You can also use the PARTITION BY clause to group the running total by a specific column.

Example:

SELECT sales, quantity, SUM(quantity) 
OVER (ORDER BY sales) as cumulative_sum 
FROM bookshop_sales;

This SQL query selects the columns order_id and quantity from the table bookshop_sales. It also creates a new column called cumulative_sum using the SUM function with the OVER clause, which calculates the cumulative sum of the sales column ordered by the order_id column.