Monthly Sales
The offers will go out next week, and the shop wants to know how its sales are doing now, so that it can compare them later: the revenue of each month.
Revenue is the money the shop got: for each item of each paid order, the quantity times the price. Take the price from order_items, where it's what the customer really paid. On Black Friday, order 28 got its games cheaper than games.price says.
To group orders by month, you need the month of each order, and strftime() makes it from the date: strftime('%Y-%m', ordered_at) gives the year and the month, such as '2025-11', and strftime('%Y', ordered_at) just the year:
SELECT id, ordered_at,
strftime('%Y-%m', ordered_at) AS month,
strftime('%Y', ordered_at) AS year
FROM orders
WHERE id IN (4, 17, 28);| id | ordered_at | month | year |
|---|---|---|---|
| 4 | 2024-03-15 | 2024-03 | 2024 |
| 17 | 2025-03-03 | 2025-03 | 2025 |
| 28 | 2025-11-28 | 2025-11 | 2025 |
Give such a column an alias, and you can use it in GROUP BY and ORDER BY. Months written as 'YYYY-MM' sort in the order of time, just like whole dates.
Typical mistake: counting orders with COUNT(*). After the join with order_items, each order is there once for every game in it, so COUNT(*) counts items, not orders. COUNT(DISTINCT o.id) counts each order once.
And one more trap: strftime() gives text, so compare its result with text, strftime('%Y', ordered_at) = '2025'. With the number 2025 the condition is never true, because SQLite doesn't take a number and a text for equal.
Instructions
Below the comment -- 5. Monthly sales, start with the big picture, the revenue of each year: the columns year, order_count (the number of paid orders) and revenue, sorted by year:
| year | order_count | revenue |
|---|---|---|
| 2024 | 14 | 605 |
| 2025 | 14 | 595 |
Below it, show 2025 month by month: the columns month (as 'YYYY-MM'), order_count and revenue, only for the orders of 2025, sorted by month. The result starts like this:
| month | order_count | revenue |
|---|---|---|
| 2025-02 | 1 | 35 |
| 2025-03 | 1 | 40 |
| 2025-04 | 1 | 40 |
| … | … | … |
Start programming for free
5/6