Mastering MySQL for Data AnalystsLesson 32 of 42
Lesson 32 of 42

Aggregate Window Functions: Running Totals & 7-Day Moving Averages in MySQL

Overview & Learning Objectives

Business executives track cumulative velocity throughout the month: "Are we pacing toward our monthly target?" Standard aggregate functions like `SUM()` and `AVG()` transform into cumulative running totals and rolling moving averages as soon as an `ORDER BY` clause is added inside `OVER()`. Rolling moving averages (such as 7-day or 30-day moving averages) smooth out weekend spikes and seasonal volatility to reveal true underlying trajectory.

  • Compute cumulative running totals using `SUM(metric) OVER (ORDER BY date)`.
  • Partition cumulative calculations by category or store.
  • Construct a 7-day rolling moving average using explicit sliding window frames.

Industry Standard

Standard: Analytics teams at Uber and Airbnb track 7-day moving averages (7DMA) of gross bookings to smooth daily fluctuations caused by weekend travel spikes.

Real-World Example: ScoopCraft Cumulative Monthly Revenue Pacing

ScoopCraft tracks daily revenue accumulation and computes a 7-day smoothed moving average across November 2026.

DateDaily RevCumulative Running Total (SUM OVER)7-Day Moving Average (AVG OVER)
Nov 01₹35,000.00₹35,000.00₹35,000.00 (Day 1)
Nov 02₹42,000.00₹77,000.00₹38,500.00 (Days 1-2)
Nov 07₹48,000.00₹280,000.00₹40,000.00 (7-Day Average)
Nov 08₹41,000.00₹321,000.00₹40,857.00 (Rolling 7 Days: Nov 2-8)

Syntax & Core SQL Implementation

-- Cumulative Running Total & 7-Day Moving Average in MySQL 8.0
SELECT 
    order_date,
    daily_sales,
    -- Cumulative Running Total from start of month
    SUM(daily_sales) OVER (
        PARTITION BY DATE_FORMAT(order_date, '%Y-%m')
        ORDER BY order_date
        ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
    ) AS monthly_cumulative_sales,
    -- 7-Day Rolling Moving Average (Current day + 6 previous days)
    ROUND(AVG(daily_sales) OVER (
        ORDER BY order_date
        ROWS BETWEEN 6 PRECEDING AND CURRENT ROW
    ), 2) AS rolling_7day_avg
FROM daily_sales;

Parameters & Arguments Breakdown

  • SUM() OVER (ORDER BY ...): Computes cumulative sum from beginning of partition up to the current row.
  • ROWS BETWEEN 6 PRECEDING AND CURRENT ROW: Sliding window frame encompassing exactly 7 consecutive days of records.

Sample Walkthrough (Q&A)

Question: What is the default window frame applied in MySQL when ORDER BY is present inside OVER()?

SQL Pattern: OVER(ORDER BY order_date)

Result: RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW

Explanation: Because the default frame extends to CURRENT ROW, standard SUM() naturally acts as a cumulative running total.

Common Mistakes & Limitations

  • Assuming `ROWS 6 PRECEDING` automatically handles missing calendar dates; if dates are skipped, it averages the previous 6 rows regardless of time gap.
  • Using `RANGE` instead of `ROWS` with duplicate values, which causes all tied duplicate rows to jump to the same running total sum.

Keyboard Shortcuts (MySQL Workbench)

ActionWindowsMac
Execute QueryCtrl + EnterCmd + Enter

Pro Tips & Modern Best Practices

  • Always prefer `ROWS` over `RANGE` for running totals to ensure smooth row-by-row progression during identical duplicate timestamps.
  • Combine with `DATE_FORMAT(order_date, "%Y-%m")` in `PARTITION BY` to automatically reset the running total at the start of every calendar month.