Write a SQL query to calculate the average number of items per order, where each row in order_items is one distinct item. Orders with no items count as 0 items. Return a single value rounded to 2 decimal places in column avg_items_per_order.
Input Table(s)
orders
| Column | Type | Meaning |
|---|
| order_id | INT | Order identifier (primary key) |
| customer_id | INT | Customer who placed the order, NOT NULL |
| order_date | DATE | Date the order was placed, NOT NULL |
order_items
| Column | Type | Meaning |
|---|
| item_id | INT | Item identifier (primary key) |
| order_id | INT | Order the item belongs to, NOT NULL, foreign key to orders.order_id |
| product_name | VARCHAR(100) | Product name, NOT NULL |
| quantity | INT | Units of the product, NOT NULL |
Keys: orders.order_id and order_items.item_id are primary keys. order_items.order_id references orders.order_id.
Output Contract
| Column | Type | Meaning |
|---|
| avg_items_per_order | NUMERIC | Number of order_items rows per order, averaged over every order in orders, rounded to 2 decimals |
The result is a single row, so no ordering applies.
Example
orders
| order_id | customer_id | order_date |
|---|
| 101 | 1 | 2024-01-03 |
| 102 | 2 | 2024-01-04 |
| 103 | 1 | 2024-01-10 |
order_items
| item_id | order_id | product_name | quantity |
|---|
| 1 | 101 | Bananas | 6 |
| 2 | 101 | Milk | 1 |
| 3 | 101 | Bread | 2 |
| 4 | 103 | Apples | 3 |
| 5 | 103 | Yogurt | 4 |
Expected result:
Order 101 has 3 items, order 102 has none and counts as 0, and order 103 has 2. The average is (3 + 0 + 2) / 3 = 1.667, which rounds to 1.67. Quantities play no part.
Constraints and Clarifications
-
orders
has at most 10,000 rows and
order_items
at most 100,000 rows.
-
Each
item_id
is unique, and every
order_items.order_id
matches an order in
orders
.
-
An order may have zero or more items. The item count of an order is its number of rows in
order_items
, not the sum of
quantity
.
-
The average is taken over all orders, including those with no items.