Lessons › SQL › Chapter 6: Window Functions
SQL lesson
Running totals with SUM() OVER
A running total adds up as it goes. Each row shows the total so far: itself plus every row before it. It's SUM with OVER (ORDER BY date). The ORDER BY tells SQL which way to add up. Without it, every row gets the whole total, like the last level. A moving average works the same way with AVG, but only over the last few rows, like the last 3 days. It smooths out busy and quiet days, so the trend shows.
Try this lesson free →Example
A total that grows row by row
SELECT order_date,
channel,
revenue,
SUM(revenue) OVER (ORDER BY order_date) AS running_total
FROM orders| order_date | channel | revenue | running_total |
|---|---|---|---|
| 2024-03-01 | Online | 120.5 | 120.5 |
| 2024-03-02 | In-store | 85.0 | 205.5 |
| 2024-03-03 | Online | 200.75 | 406.25 |
| 2024-03-04 | In-store | 55.25 | 461.5 |
| 2024-03-05 | Online | 310.0 | 771.5 |
Step by step
- Adds up revenue.
SELECT order_date, revenue, SUM(revenue) OVER (ORDER BY order_date) AS running_total FROM orders - Puts the answer next to each row, like the last level.
SELECT order_date, revenue, SUM(revenue) OVER (ORDER BY order_date) AS running_total FROM orders - Adds up in date order. Each row gets the total so far, not the whole total.
SELECT order_date, revenue, SUM(revenue) OVER (ORDER BY order_date) AS running_total FROM orders - AVG instead of SUM, over this row and the 2 before it: a 3-day moving average.
SELECT order_date, revenue, SUM(revenue) OVER (ORDER BY order_date) AS running_total FROM orders
Practice
1. Using orders, show order_date, revenue and the running total of revenue by date. Name it running_total.
SELECT order_date, revenue, SUM(revenue) OVER (ORDER BY order_date) AS running_total FROM orders2. Using orders, keep a separate running total for each channel.
SELECT order_date, channel, revenue, SUM(revenue) OVER (PARTITION BY channel ORDER BY order_date) AS running_total FROM orders3. Using daily_sales, show sale_date, revenue and the 3-day moving average of revenue. Name it moving_avg.
SELECT sale_date, revenue, AVG(revenue) OVER (ORDER BY sale_date ROWS BETWEEN 2 PRECEDING AND CURRENT ROW) AS moving_avg FROM daily_sales4. Using store_sales, show sale_date, revenue and the revenue so far by date. Name it running_total.
SELECT sale_date, revenue, SUM(revenue) OVER (ORDER BY sale_date) AS running_total FROM store_sales5. Using employees, show hire_date, salary and the total payroll so far as each person was hired. Name it payroll_so_far.
SELECT hire_date, salary, SUM(salary) OVER (ORDER BY hire_date) AS payroll_so_far FROM employeesLearn it by doing. This lesson is a short hands-on level on Bampaa: see it work, then build and write it yourself, with instant feedback.
Try this lesson free →