Introduction
Running totals help you see the sum of values up to each row, like keeping a growing score in a game.
SELECT column1, column2, SUM(column_to_sum) OVER (ORDER BY column_to_order) AS running_total FROM table_name;
SELECT date, sales, SUM(sales) OVER (ORDER BY date) AS running_total FROM daily_sales;
SELECT id, points, SUM(points) OVER (ORDER BY id) AS cumulative_points FROM game_scores;
SELECT month, expense, SUM(expense) OVER (ORDER BY month) AS total_expense FROM monthly_expenses;
CREATE TABLE sales ( day INT, amount INT ); INSERT INTO sales (day, amount) VALUES (1, 100), (2, 150), (3, 200), (4, 50); SELECT day, amount, SUM(amount) OVER (ORDER BY day) AS running_total FROM sales ORDER BY day;
SUM(amount) OVER (ORDER BY date) calculate?sales ordered by sale_date?sales_data with columns id, sale_date, and amount, what is the output of this query?SELECT id, sale_date, amount, SUM(amount) OVER (ORDER BY sale_date) AS running_total FROM sales_data ORDER BY id;
id | sale_date | amount
1 | 2024-01-01 | 100
2 | 2024-01-03 | 200
3 | 2024-01-02 | 150points ordered by game_date:SELECT player_id, points, SUM(points) OVER (PARTITION BY player_id) ORDER BY game_date FROM game_scores;
region, sale_date, and amount. You want to calculate a running total of sales per region ordered by sale_date. Which query correctly achieves this?Pass the test and this pattern moves unknown