// window reference

SQL moving sum

Sums only the rows inside the frame: a trailing n-row (or n-day) window that slides with the current row.

Catégorie
Fenêtre
Returns
numeric
In this category
33 of 79

Syntaxe

SUM(x) OVER (ORDER BY d ROWS BETWEEN 29 PRECEDING AND CURRENT ROW) | SUM(x) OVER (ORDER BY d ROWS BETWEEN 2 PRECEDING AND 1 FOLLOWING)

Prise en charge des moteurs

MoteurSupportNotes
SQL Server Oui Supported under this name.
PostgreSQL Oui Supported under this name.
MySQL Oui MySQL 8.0+
SQLite Oui SQLite 3.25+
Oracle Oui Supported under this name.

Exemples

Any engine

-- trailing 30-row sum per store
SELECT store_id, day, units,
       SUM(units) OVER (PARTITION BY store_id ORDER BY day
                        ROWS BETWEEN 29 PRECEDING AND CURRENT ROW) AS sum30
FROM daily_sales;

Bon à savoir

  • FOLLOWING bounds look ahead: with one row per week, the current and next two weeks is ROWS BETWEEN CURRENT ROW AND 2 FOLLOWING, and the last rows of the partition see a shorter window.
  • A window sum is not a total: with a bounded frame it deliberately excludes older rows. Check the frame before assuming a 'SUM OVER' is a grand total.
  • ROWS is positional: with duplicate ORDER BY values the engine picks which tied row falls just inside the frame, so the sum can change between runs. Add a unique tiebreaker.

Questions about Moving Sum

How do I sum the next N rows instead of the previous ones?

Use FOLLOWING as the end boundary: SUM(x) OVER (ORDER BY d ROWS BETWEEN CURRENT ROW AND 6 FOLLOWING). Boundaries can mix one PRECEDING and one FOLLOWING.

Why not just write SUM(x) OVER (ORDER BY d)?

That uses the default frame, RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW: a running total from the first row, not a sliding window. A moving sum needs an explicit bounded frame: ROWS for n rows, RANGE with an offset for an n-unit value span.

Browse every function in the SQL function reference, or see what the SQLly desktop app does for your database.

Cheat sheets for the engines that have it: SQL Server, PostgreSQL, MySQL, SQLite, Oracle.

// fewer lookups

Functions your engine actually has

SQLly's completion lists the built-in functions of the engine you're connected to, whether that's SQL Server, PostgreSQL, MySQL, SQLite or Oracle. Hover a function for help, and signature hints show each argument as you type.