SQL-Engineering-Handbook

Running Totals and Running Averages

Running total accumulation diagram using SUM() OVER()

Overview

Aggregate functions (SUM(), AVG(), COUNT(), MIN(), MAX()) can be used as window functions by adding an OVER() clause with ORDER BY. This produces a cumulative (running) calculation instead of a single collapsed value.

Learning Objectives

Prerequisites

Syntax

SUM(column) OVER (ORDER BY sort_column) AS running_total

AVG(column) OVER (
    PARTITION BY group_column
    ORDER BY sort_column
) AS running_average_per_group

Dataset Used

employes joined to departments

Examples

See 07_running_totals.sql.

Real World Applications

Business Use Cases

Domain Scenario
Banking Running account balance after each transaction
Finance Cumulative revenue-to-date, YTD tracking
Retail Rolling 7-day average sales for demand forecasting
Logistics Cumulative distance travelled per route

Common Mistakes

Best Practices

Engineering Notes

Running totals computed this way are O(n) per partition after the initial sort, versus the O(n²) cost of the classic self-join/correlated subquery pattern (SUM(...) WHERE b.id <= a.id). This is one of the clearest performance wins window functions offer over pre-window-function SQL patterns.

Practice Questions

  1. Create a running total of emp_id using SUM() OVER().
  2. Create a running average of emp_id using AVG() OVER().
  3. (Bonus) Restart the running total per department using PARTITION BY.
  4. (Bonus) Compute each employee’s contribution to the running total as a percentage of the final cumulative value.

Difficulty

Intermediate

Estimated Time

25–30 minutes

Learning Outcomes

Next Topic

08_Subqueries_Advanced (or the next module in your handbook sequence)


Lesson Navigation

← Previous: 06_FIRST_LAST_NTILEModule README → Next: This is the final lesson in this module — see the Module README for the full roadmap.