SQL RANGE with interval offsets
When the ORDER BY is a date or timestamp, RANGE offsets can be intervals: the frame covers a time span, independent of how many rows exist.
- Категория
- Окно
- Returns
per-frame aggregate- In this category
- 61 of 79
Синтаксис
AVG(x) OVER (ORDER BY ts RANGE BETWEEN INTERVAL '6 days' PRECEDING AND CURRENT ROW)
Поддержка движка
| Движок | Support | Заметки |
|---|---|---|
| SQL Server | Not built in | No built-in equivalent. |
| PostgreSQL | Да | RANGE ... INTERVAL ... PRECEDING / FOLLOWING on temporal ORDER BY |
| MySQL | Да | MySQL 8.0+ allows interval units in RANGE frames: RANGE BETWEEN INTERVAL 6 DAY PRECEDING AND CURRENT ROW |
| SQLite | Not built in | RANGE offsets are integers only, no interval type; emulate with date arithmetic and RANGE on julian day or a generated date spine |
| Oracle | Да | RANGE BETWEEN INTERVAL '6' DAY PRECEDING AND CURRENT ROW, and NUMTODSINTERVAL forms |
Примеры
PostgreSQL
SELECT day, price,
AVG(price) OVER (ORDER BY day
RANGE BETWEEN INTERVAL '6 days' PRECEDING AND CURRENT ROW) AS ma7d
FROM prices;
Oracle
SELECT trade_ts, amount,
SUM(amount) OVER (ORDER BY trade_ts
RANGE BETWEEN INTERVAL '1' HOUR PRECEDING AND CURRENT ROW) AS hourly_vol
FROM trades;
Полезно знать
- Interval frames solve the gap problem: a 7-day window keeps being 7 days when days are missing, whereas ROWS BETWEEN 6 PRECEDING quietly stretches over holes.
- SQL Server has no interval offsets (its RANGE has none at all): the standard workaround is a calendar spine joined to the data, or ROWS with an explicit row count.
- The interval must match the ORDER BY type: a DAY interval on a plain DATE, a SECOND-capable interval on timestamps; mixing date and numeric semantics is an error.
Questions about RANGE Interval Frames
Why prefer an interval frame over ROWS for time data?
Because ROWS counts observations: a day with no sales shifts the 7-day window into week-old data. RANGE with an interval anchors the window to the clock, giving real 'last 7 days' semantics.
How do I do this on SQL Server or SQLite?
SQLite: order by julianday(day) and use RANGE BETWEEN 6 PRECEDING AND CURRENT ROW, which is a numeric offset in days. SQL Server has no RANGE offsets, so join a calendar table to fill missing days and use ROWS, or use a correlated subquery over the date range.
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: PostgreSQL, MySQL, 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.