Date Operations & Time-Based Analytics SQL Topic exerciseHardVerified answerSQLite + PostgreSQL + MySQL + SQL Server live · 1 guided

Cumulative Sum with Monthly Reset

Return each order with a cumulative monthly amount in chronological order.

  • Window functions
  • Aggregation
  • Date analysis
  • Type conversion
  • Sorting

Exercise brief

Understand the request

Finance operations lead A transaction ledger needs a running amount that restarts at each calendar month.

A transaction ledger needs a running amount that restarts at each calendar month. Return each order with a cumulative monthly amount in chronological order.

Return

  • Return order_date, order_total, cumulative_amount_month in this exact left-to-right order.

Constraints

  • Partition the running total by year-month.
  • Use an explicit ROWS frame.
  • Use order_id as a stable tie-breaker within a date.

Data you will use

Review the relevant tables before deciding how to join, filter, or aggregate them.

orders

  • order_idINTEGER
  • order_dateDATE
  • order_totalDECIMAL

Hints, when you need them

Open one clue at a time so you still do the reasoning.

Hint 1

A running total that resets monthly = PARTITION BY the month key.

Hint 2

Build the month key with strftime('%Y-%m', order_date) (or DATE_TRUNC / DATE_FORMAT).

Hint 3

ORDER BY within the window controls the accumulation order.

Verified SQL answer

Attempt the problem first, then compare structure and reasoning—not just syntax.

Reveal solution and explanation
SELECT order_date, order_total, CAST(SUM(order_total) OVER (PARTITION BY strftime('%Y-%m', order_date) ORDER BY order_date, order_id ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS INTEGER) AS cumulative_amount_month FROM orders ORDER BY order_date, order_id;

Why this works

Partitioning a windowed SUM by the month key restarts the accumulation each month — a common 'within-period running total'. The only engine difference is how you derive the month-bucket key for PARTITION BY. With distinct order dates the default frame is fine; for tied dates add an explicit ROWS frame.

Success check

Every order remains at transaction grain and each month begins a new deterministic cumulative total.

Expected result

Use this output to verify values, aliases, ordering, and row count.

order_dateorder_totalcumulative_amount_month
2023-01-10200200
2023-02-15340340
2024-01-15250250
2024-01-20180430
2024-02-10320320
2024-02-25150470
2024-03-05420420
2024-03-15280700
2024-04-01190190
2024-04-10350540

Previewing 10 of 20 expected rows. Run the query in the editor to inspect the full result.

Learn the concepts behind this answer

Strengthen your understanding with these targeted learning topics:

Continue practicing

SQL Practice Online

Open the interactive workspace and practice across SQL topics.