Branch Energy Spend vs Chain Average
Problem
Table: `energy_bill`
| Column Name | Type |
|---|---|
| bill_id | int |
| store_id | int |
| cost | int |
| billed_on | date |
`bill_id` is the primary key. Each row is one store's energy cost for a billing date.
Table: `store`
| Column Name | Type |
|---|---|
| store_id | int |
| region_id | int |
`store_id` is the primary key; `region_id` says which region the store belongs to.
For each calendar month, compare the average energy `cost` of each **region** against the average energy cost of the **whole chain** in that same month. Report `bill_month` (formatted `YYYY-MM`), `region_id`, and `verdict` which is `'higher'`, `'lower'`, or `'same'` depending on how the region average compares to the chain average. A bill counts toward both averages once. Order by `bill_month` descending, then `region_id` ascending.
Tables
Example rows — the live problem includes the full dataset.
| bill_id | store_id | cost | billed_on |
|---|---|---|---|
| 1 | 1 | 9000 | 2024-03-31 |
| 2 | 2 | 6000 | 2024-03-31 |
| 3 | 3 | 10000 | 2024-03-31 |
| store_id | region_id |
|---|---|
| 1 | 1 |
| 2 | 2 |
| 3 | 2 |
Expected output
Your answer should return 4 rows with the columns bill_month, region_id, verdict.
Starter code (SQL)
SELECT *
FROM energy_bill;Solve this SQL question free
Write SQL and run it instantly in your browser — even on your phone. No signup needed to try.
Solution & explanation
Create a free account to unlock the optimal solution, a step-by-step explanation, and the hidden test cases that grade your answer.
Sign up free to unlock