Full answer
sql
WITH t(id, day, amount) AS (VALUES (1, 1, 10), (2, 2, 5), (3, 2, 7), (4, 3, 1))
SELECT id, day, amount,
SUM(amount) OVER (ORDER BY day, id ROWS BETWEEN 1 PRECEDING AND CURRENT ROW) AS rows_sum,
SUM(amount) OVER (ORDER BY day GROUPS BETWEEN 1 PRECEDING AND CURRENT ROW) AS groups_sum
FROM t ORDER BY id;| id | day | amount | rows_sum | groups_sum |
|---|---|---|---|---|
| 1 | 1 | 10 | 10 | 10 |
| 2 | 2 | 5 | 15 | 22 |
| 3 | 2 | 7 | 12 | 22 |
| 4 | 3 | 1 | 8 | 13 |
Day 2 has two rows. With ROWS, the second day-2 row sums itself and the row just before it (the other day-2 row). With GROUPS, every day-2 row sums all of day 2 plus all of day 1, because the frame is measured in groups of equal day values.
GROUPS is the natural choice for "this day and the previous day" when days can have several rows and every day is present. If days can be missing, use RANGE with a numeric offset on a day number instead, since GROUPS also ignores gaps.
sql
WITH t(id, day, amount) AS (VALUES (1, 1, 10), (2, 2, 5), (3, 2, 7), (4, 3, 1))
SELECT id, day, amount,
SUM(amount) OVER (ORDER BY day, id ROWS BETWEEN 1 PRECEDING AND CURRENT ROW) AS rows_sum,
SUM(amount) OVER (ORDER BY day GROUPS BETWEEN 1 PRECEDING AND CURRENT ROW) AS groups_sum
FROM t ORDER BY id;Checked on SQLite 3.46.1, run twice with identical output.
Key points
- ROWS counts physical rows
- GROUPS counts peer groups of equal ORDER BY values
- GROUPS includes whole groups at each end
- Supported in SQLite 3.28+ and PostgreSQL 11+
Common mistakes
- Using ROWS for per-day windows when days have several rows
- Assuming GROUPS skips missing days correctly
Follow-ups
- How would RANGE BETWEEN 1 PRECEDING work here?
- What does EXCLUDE TIES do?
Tips
- Point to a duplicate-day row