Monthly revenue and the change from the month before
Hard · Online shop database · Window functions, WITH (CTE), Date functions
Work out the revenue of each month from delivered orders (quantity times unit_price, summed). Months without delivered orders are not listed, so each month is compared with the previous month in the list.
Return the month as YYYY-MM, its revenue, and the change (this month's revenue minus the previous listed month's), both rounded to 2 decimals with round, in that order, sorted by month. The first month's change is NULL.
Expected result
| month | revenue | change |
|---|---|---|
| 2025-02 | 255.94 | NULL |
| 2025-03 | 89.5 | -166.44 |
| 2025-04 | 152.99 | 63.49 |
| 2025-05 | 180.99 | 28 |
| 2025-06 | 82.43 | -98.56 |
| 2025-07 | 119 | 36.57 |
| 2025-08 | 96.88 | -22.12 |
| 2025-10 | 112.49 | 15.61 |
| 2025-11 | 39 | -73.49 |
| 2025-12 | 155.48 | 116.48 |
| 2026-01 | 235 | 79.52 |
| 2026-02 | 58.47 | -176.53 |
| 2026-03 | 146.5 | 88.03 |
The online shop tables
customers: 18 rows, first 5 shown
| id | name | city | country | signup_date | phone |
|---|---|---|---|---|---|
| 1 | Ravi Kumar | Bengaluru | India | 2025-01-12 | +91 98450 12345 |
| 2 | Emily Johnson | Austin | USA | 2025-01-25 | +1 512 555 0142 |
| 3 | Hiroshi Sato | Osaka | Japan | 2025-02-08 | NULL |
| 4 | Ana Souza | Sao Paulo | Brazil | 2025-02-19 | +55 11 91234 5678 |
| 5 | Priya Sharma | Mumbai | India | 2025-03-03 | +91 99200 54321 |
order_items: 40 rows, first 5 shown
| id | order_id | product_id | quantity | unit_price |
|---|---|---|---|---|
| 1 | 1 | 1 | 1 | 22.99 |
| 2 | 1 | 9 | 3 | 3.99 |
| 3 | 2 | 4 | 1 | 189 |
| 4 | 2 | 16 | 2 | 15.99 |
| 5 | 3 | 2 | 1 | 89.5 |
orders: 28 rows, first 5 shown
| id | customer_id | order_date | status |
|---|---|---|---|
| 1 | 1 | 2025-02-03 | delivered |
| 2 | 2 | 2025-02-14 | delivered |
| 3 | 3 | 2025-03-01 | delivered |
| 4 | 1 | 2025-03-22 | cancelled |
| 5 | 4 | 2025-04-05 | delivered |
products: 18 rows, first 5 shown
| id | name | category | price | stock |
|---|---|---|---|---|
| 1 | Wireless Mouse | Electronics | 24.99 | 120 |
| 2 | Mechanical Keyboard | Electronics | 89.5 | 45 |
| 3 | USB-C Hub | Electronics | 39 | 80 |
| 4 | Noise Cancelling Headphones | Electronics | 199 | 25 |
| 5 | Intro to Statistics | Books | 48 | 60 |
-- Write your SQL here