SQL Intermediate Lesson 3: Running Totals and Moving Averages

SQL Intermediate Lesson 3: Running Totals and Moving Averages 1

📎 This article includes 2 downloadable practice files ↓

⏱ 2 min read

📘 SQL Intermediate Course · Lesson 3 of 10

Advertisement

Aggregate functions become running calculations when you add OVER with an ORDER BY.

WITH m AS (SELECT month, SUM(amount) AS total FROM sales GROUP BY month)
SELECT month, total,
       SUM(total) OVER (ORDER BY month)                                   AS running_total,
       AVG(total) OVER (ORDER BY month ROWS BETWEEN 2 PRECEDING AND CURRENT ROW) AS moving_avg_3,
       100.0 * total / SUM(total) OVER ()                                  AS pct_of_total
FROM m;
Window Meaning
OVER () All rows: grand total on every row
OVER (ORDER BY month) From the first row up to this one: running total
OVER (PARTITION BY region ORDER BY month) Running total restarting for each region (YTD by region)
ROWS BETWEEN 2 PRECEDING AND CURRENT ROW This row and the two before: 3-month moving window
⚠️ With ORDER BY and no frame, the default is RANGE ... CURRENT ROW, which includes all rows with the same value. If two rows share a date, both get the same running total. Use ROWS or add a tie-breaker.

Common mistakes

  • Running totals on unaggregated rows when you wanted monthly ones: aggregate in a CTE first.
  • Moving average at the start covers fewer months (1, then 2). Filter those rows out if you need a full window.

Practice

Download shop2.db and this lesson’s exercise file below. Open the database in DB Browser for SQLite (free), paste each task into the Execute SQL tab and compare with the expected result printed under it. Answers are at the bottom of the file.

📎 Practice files for this article

⬇ Download all 2 files (ZIP · 9 KB)

  • 📄
    Practice database (SQLite)shop2.db: customers, products, 300 orders, payments, employees with managers and monthly targets.
    ⬇ DB · 48 KB
  • 🗃️
    Lesson 3 exercisesTasks with the real expected result under each, and answers at the bottom.
    ⬇ SQL · 4 KB

Free to use for learning. Files with macros (.bas) are plain text — import them with Alt+F11 → File → Import File, and always test on a copy.

Advertisement
✨ Ask AI about this article

Stuck on a step? Ask a question and the AI answers using this article.

Free · AI can be wrong