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

Monthly Revenue Summary (Portable Month Bucketing)

Return order count and revenue by year-month across the full dataset.

  • Aggregation
  • Date analysis
  • Numeric functions
  • Sorting

Exercise brief

Understand the request

Business intelligence developer A portable monthly trend feed needs a stable sortable period key.

A portable monthly trend feed needs a stable sortable period key. Return order count and revenue by year-month across the full dataset.

Return

  • Return order_month, order_count, monthly_revenue in this exact left-to-right order.

Constraints

  • Bucket dates at calendar-month grain.
  • Keep a chronologically sortable period value.
  • Order by order_month.

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

Bucketing by month means deriving a 'YYYY-MM' label (or truncating to the 1st of the month).

Hint 2

GROUP BY the same month expression you SELECT.

Hint 3

SQLite: strftime('%Y-%m', d). Postgres: DATE_TRUNC('month', d). MySQL: DATE_FORMAT. SQL Server: FORMAT.

Verified SQL answer

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

Reveal solution and explanation
SELECT strftime('%Y-%m', order_date) AS order_month, COUNT(*) AS order_count, ROUND(SUM(order_total), 2) AS monthly_revenue FROM orders GROUP BY strftime('%Y-%m', order_date) ORDER BY order_month;

Why this works

Grouping by month is the single most common date task in analytics, and the canonical place engines diverge. Memorize the four idioms: SQLite strftime('%Y-%m'), Postgres DATE_TRUNC('month', d) (keeps a real date), MySQL DATE_FORMAT(d,'%Y-%m'), SQL Server FORMAT(d,'yyyy-MM'). DATE_TRUNC is preferred when you need a real date to sort or join on.

Success check

Every populated month appears once with correct order count and revenue.

Expected result

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

order_monthorder_countmonthly_revenue
2023-011200
2023-021340
2024-012430
2024-022470
2024-032700
2024-042540
2024-052600
2024-062700
2024-071330
2024-081270

Previewing 10 of 14 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.