0Pricing
SQL Academy · Lesson

Running Totals and Moving Averages

Compute running sums and moving averages with SUM(...) OVER (ORDER BY ... ROWS BETWEEN ...).

Running Total Basics

A running total is a SUM with ORDER BY in the window — and no frame clause, so the default frame is "from the start to the current row":

SELECT day, revenue,
       SUM(revenue) OVER (ORDER BY day) AS running_total
FROM daily_revenue
ORDER BY day;

Per-Group Running Total

Reset the running total per user:

SELECT id, user_id, total,
       SUM(total) OVER (
         PARTITION BY user_id ORDER BY created_at
       ) AS user_running_total
FROM orders;

All lessons in this course

  1. OVER, PARTITION BY, ORDER BY
  2. ROW_NUMBER, RANK, DENSE_RANK
  3. LAG, LEAD and Time-Series Patterns
  4. Running Totals and Moving Averages
← Back to SQL Academy