Problem Statement
How do you compute an account running balance that resets when a new month starts?
Explanation
Partition the window by account and the month key so the cumulative sum restarts for each month. Order by transaction time and add a stable id as a tie breaker.
This produces a per-month running total without extra joins or procedural loops.
Code Solution
SolutionRead Only
SUM(amount) OVER (
PARTITION BY account_id, date_trunc('month', txn_time)
ORDER BY txn_time, id
ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
) AS month_running_balance