download

How do you reset a running total every month?

SQL~9 minReviewed 2 Dec 2026Free · No sign-in

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

monthposting_dateposting_idamount_cents
2026-102026-10-04103000
2026-102026-10-04112500
2026-102026-10-2212-1300
2026-112026-11-02141300
2026-112026-11-0215700
Show hints (2)
  1. "CHOOSE THE PARTITION"

    Decide which column starts a fresh total.

  2. "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.

"SOLUTION · SQL"
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;
"OUTPUT"
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 →

Original OfferVibe question. SQLite window functions.
© 2026 OfferVibe · Text CC BY-NC-SA 4.0 · code MITFree to share and adapt with credit, not for commercial use. Code samples are free for any use.