You have a customers table and an orders table. Join them on customer_id and return the average order amount for each state. Only states with at least one matching order belong in the result.
Input Table(s)
Table customers (primary key customer_id):
| Column | Type | Meaning |
|---|
| customer_id | INT | Unique customer identifier |
| customer_name | VARCHAR(100) | Customer's name |
| state | VARCHAR(50) | The customer's state |
Table orders (primary key order_id; customer_id is a foreign key to customers.customer_id):
| Column | Type | Meaning |
|---|
| order_id | INT | Unique order identifier |
| customer_id | INT | Customer who placed the order |
| amount | DECIMAL(10,2) | Order amount |
| order_date | DATE | Date the order was placed |
Output Contract
-
Columns, in this order:
state
,
avg_order_amount
.
-
One row per state that has at least one order.
-
avg_order_amount
is the mean of
amount
across every order placed by a customer in that state, rounded to 2 decimal places.
-
Sort by
avg_order_amount
descending (the rounded value), then by
state
ascending. Each state appears once, so this order is unique.
Example
customers
| customer_id | customer_name | state |
|---|
| 1 | Ana | CA |
| 2 | Ben | TX |
| 3 | Cara | CA |
| 4 | Dev | NY |
| 5 | Eli | WA |
| 6 | Gus | FL |
orders
| order_id | customer_id | amount | order_date |
|---|
| 101 | 1 | 60.00 | 2026-01-03 |
| 102 | 1 | 30.00 | 2026-01-10 |
| 103 | 3 | 30.00 | 2026-02-01 |
| 104 | 2 | 40.00 | 2026-02-14 |
| 105 | 5 | 10.00 | 2026-03-01 |
| 106 | 5 | 20.00 | 2026-03-02 |
| 107 | 5 | 70.00 | 2026-03-05 |
| 108 | 6 | 85.25 | 2026-03-09 |
Expected output:
| state | avg_order_amount |
|---|
| FL | 85.25 |
| CA | 40.00 |
| TX | 40.00 |
| WA | 33.33 |
CA has three orders (60.00, 30.00 and 30.00 from two customers), so its average is 120.00 / 3 = 40.00. WA averages 100.00 / 3 = 33.333..., which rounds to 33.33. CA and TX tie at 40.00, so CA comes first by name. NY has a customer but no orders, so it does not appear.
Constraints and Clarifications
-
The
customers
table has 1 to 10,000 rows and the
orders
table has 1 to 100,000 rows.
-
Every
orders.customer_id
matches an existing
customers.customer_id
.
-
amount
is non-negative and
state
is never NULL.
-
The average is per order. A customer with three orders contributes three amounts to their state's average, and a customer with one order contributes one.
-
States whose customers placed no orders are left out of the output.
-
Two states whose rounded averages are equal are ordered by
state
ascending.
-
amount
is not expected to be NULL. If one were, it should be left out of the average, which is what
AVG
does by default.
-
order_date
is not needed for this query.