How do you reset a running total every month?
Question
Return a running balance in cents after each posting. Reset it each month. Within a month, process rows by date and then unique posting ID. A negative amount reduces the balance. Return the month, posting ID, and balance in that order.
postings
| month | posting_date | posting_id | amount_cents |
|---|---|---|---|
| 2026-10 | 2026-10-04 | 10 | 3000 |
| 2026-10 | 2026-10-04 | 11 | 2500 |
| 2026-10 | 2026-10-22 | 12 | -1300 |
| 2026-11 | 2026-11-02 | 14 | 1300 |
| 2026-11 | 2026-11-02 | 15 | 700 |
Show hints (2)
- "CHOOSE THE PARTITION"
Decide which column starts a fresh total.
- "INCLUDE ONLY PRECEDING ROWS"
Use a stable posting order and a frame that ends at the current row.
Show checked explanation
Partition SUM() by month and order it by date and posting ID. Use a frame from the first row of the month through the current posting.
SELECT month, posting_id, SUM(amount_cents) OVER ( PARTITION BY month ORDER BY posting_date, posting_id ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW ) AS balance_cents FROM postings ORDER BY month, posting_date, posting_id;
month | posting_id | balance_cents 2026-10 | 10 | 3000 2026-10 | 11 | 5500 2026-10 | 12 | 4200 2026-11 | 14 | 1300 2026-11 | 15 | 2000
Ran the query on SQLite 3.49 with the sample rows and edge cases.
Walkthrough
October starts at 3000. The next posting on the same day raises the balance to 5500. A refund reduces it to 4200. November starts from its own first posting at 1300. Including posting ID in the window order defines which of the same-day entries goes first.
Common mistakes
- Using
GROUP BY month, which removes the individual postings. - Omitting the partition and carrying October's balance into November.
- Ordering only by date. A row-based frame still needs a stable order for postings on the same day.
Follow-up questions
- "What if you need totals per account and month?" Partition by both account ID and month so each account starts its own monthly balance.
- "What can happen with the default frame if you order only by date?" Rows on the same date are peers. The default frame can include all peers, so both opening October rows show 5500.
What a strong answer covers
Keep one output row per posting. Name both the reset boundary and the order inside it.
Open in interactive practice deck →