A Running Total with an Ordered Window

An ordered window can sum rows from a partition's start through the current row according to a specified frame.

Source
Anbloq
Language
English
Created
Updated
Chapters
4
Reading time
1 min
In this article4 chapters
  1. Trace three daily values
  2. Check tied order values
  3. Make peer rows and the window frame explicit
  4. Test both ties and resets between partitions

Trace three daily values

Amounts 2, 6, and minus 1 in that order have totals 2, 8, and 7. Prefix totals express the same accumulation outside SQL.

Check tied order values

Rows sharing a date can share a range frame boundary. If each row should advance the running total, choose a suitable row frame and deterministic order. See row numbering.[1]

Make peer rows and the window frame explicit

Entries with amounts three, four and negative two produce running totals three, seven and five in ID order. If timestamps tie, ordering by timestamp alone may give peers the same total under a default range frame. Use a deterministic tie-break and an explicit rows frame for a record-by-record total. See prefix totals.

WITH entries(id, amount) AS (VALUES (1,3), (2,4), (3,-2))
SELECT id, SUM(amount) OVER (ORDER BY id ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW)
FROM entries ORDER BY id;
-- Expected totals: 3, 7, 5.

Test both ties and resets between partitions

An accounting group can restart the total by partitioning on account. Test a negative adjustment, tied timestamps and a second account.

References

  1. PostgreSQL Global Development Group, Window Functions Tutorial ↩