SQL moving sum
Sums only the rows inside the frame: a trailing n-row (or n-day) window that slides with the current row.
- 카테고리
- 창
- Returns
numeric- In this category
- 33 of 79
구문
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)
엔진 지원
| 엔진 | Support | 메모 |
|---|---|---|
| SQL Server | 예 | Supported under this name. |
| PostgreSQL | 예 | Supported under this name. |
| MySQL | 예 | MySQL 8.0+ |
| SQLite | 예 | SQLite 3.25+ |
| Oracle | 예 | Supported under this name. |
예시
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;
알아 두면 좋은 정보
- 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.
Related on SQLly
Cheat sheets for the engines that have it: SQL Server, PostgreSQL, MySQL, SQLite, Oracle.
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.