How can I calculate a running total with a window function?
Quick answer
Use SUM(amount) OVER (...) with an ORDER BY inside the window and a frame from the first row through the current row. For example, ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW includes expenses up to that point in the chosen sequence. Add a stable tie-breaker if dates repeat, and use the query’s outer ORDER BY to control display order. [S1]
The question, the details, the next step.
A practical checklist
Replace the example table and column names with those in your schema.
Choose the column that defines the running sequence, such as the date.
Add a stable tie-breaker when multiple rows can share the ordering value.
Use the explicit frame from
UNBOUNDED PRECEDINGthroughCURRENT ROWfor a row-by-row accumulation.Add an outer
ORDER BYif displayed results should follow the calculation sequence.Use an outer query when filtering on the calculated running total.
A few more useful answers
Does the window ORDER BY also sort the final results?
Not by itself. The window ordering defines the calculation sequence; use an outer ORDER BY to specify displayed row order. [S1]
Why include a tie-breaker in the window ordering?
When dates repeat, a tie-breaker such as an expense ID defines which tied row comes first in the calculation sequence. [S1]
Can I filter directly on running_total in the same query?
In SQLite, put the window calculation in a subquery, then filter on its result in the outer query. [S1]
Sources
References used for this guide.
- [S1] SQLite window functions: aggregate functions and window ordering sqlite.org · Checked
