Change from the previous month
Hardrow order matters
For each month, show orders and change: orders minus the previous month's orders (NULL for the first month), in month order.
Tables: customers(customer_id, name, city, country, joined) · products(product_id, name, category, price) · orders(order_id, customer_id, order_date, status) · order_items(order_id, product_id, quantity, unit_price)
Your query✔ Solved
Show the expected result
| month | orders | change |
|---|---|---|
| 2025-01 | 2 | NULL |
| 2025-02 | 3 | 1 |
| 2025-03 | 8 | 5 |
| 2025-04 | 5 | -3 |
| 2025-05 | 5 | 0 |
| 2025-06 | 2 | -3 |
| 2025-07 | 5 | 3 |
| 2025-08 | 6 | 1 |
| 2025-09 | 2 | -4 |
| 2025-10 | 6 | 4 |
| 2025-11 | 3 | -3 |
| 2025-12 | 4 | 1 |
12 rows
Show a solution
WITH m AS (SELECT strftime('%Y-%m', order_date) AS month, COUNT(*) AS orders FROM orders GROUP BY month) SELECT month, orders, orders - LAG(orders) OVER (ORDER BY month) AS change FROM m ORDER BY month;
SQL used
New to SQL? The free SQL course teaches everything these problems use, with a self-checking exercise in every lesson.