Write SQL to calculate a running total without collapsing the original rows.
Answer
Use SUM as a window aggregate with PARTITION BY when totals restart per entity and ORDER BY in the event sequence. Specify an explicit ROWS frame and deterministic ordering when multiple rows can share the same timestamp, otherwise peer rows may make cumulative results surprising.
Strong answer includes
- uses SUM as a window function rather than GROUP BY
- defines partition and deterministic event order
- understands the effect of the window frame
Practical example
Dialect · Portable SQLRuntime · SQLite sample DB
Runs against the resettable SQLite sample database used by the playground.
SQL
Result
Run the query to see the result.
Use SUM as a window aggregate ordered by the sequence of events. An explicit ROWS frame avoids peer-group surprises when several rows share the same ordering value.
Expected result: Every source row plus its cumulative total at that point.