You are given two tables: Orders and Items. The Orders table contains information about orders placed by customers, and the Items table contains item details including categories.
As a business owner, you need to create a sales report showing how many units of each item category have been ordered on each day of the week.
Write a SQL query to return the total quantity ordered for each category on each day of the week (Monday through Sunday).
Requirements:
- Show results for all 7 days of the week, even if no orders were placed
- Show results for all categories that appear in orders
- Use 0 for days/categories with no orders
- Order results by category name
Table Schema
| Column Name | Type | Description |
|---|---|---|
order_id
PK
|
int | Order identifier |
customer_id
|
int | Customer who placed the order |
order_date
|
date | Date when the order was placed |
item_id
PK
|
varchar | Item that was ordered |
quantity
|
int | Number of units ordered |
| Column Name | Type | Description |
|---|---|---|
item_id
PK
|
varchar | Unique item identifier |
item_name
|
varchar | Name of the item |
item_category
|
varchar | Category the item belongs to |
Input & Output
| order_id | customer_id | order_date | item_id | quantity |
|---|---|---|---|---|
| 1 | 1 | 2020-06-01 | 10 | 10 |
| 2 | 1 | 2020-06-08 | 20 | 10 |
| 3 | 2 | 2020-06-02 | 30 | 5 |
| 4 | 3 | 2020-06-03 | 40 | 5 |
| 5 | 4 | 2020-06-04 | 10 | 15 |
| item_id | item_name | item_category |
|---|---|---|
| 10 | laptop | Electronics |
| 20 | C++ | Books |
| 30 | mouse | Electronics |
| 40 | keyboard | Electronics |
| item_category | Monday | Tuesday | Wednesday | Thursday | Friday | Saturday | Sunday |
|---|---|---|---|---|---|---|---|
| Books | 10 | 0 | 0 | 0 | 0 | 0 | 0 |
| Electronics | 10 | 5 | 5 | 15 | 0 | 0 | 0 |
The query joins Orders with Items to get categories, then groups by category and day of week. June 1st 2020 was a Monday (laptop: 10 units), June 2nd was Tuesday (mouse: 5 units), June 3rd was Wednesday (keyboard: 5 units), June 4th was Thursday (laptop: 15 units), and June 8th was Monday (C++ book: 10 units).
| order_id | customer_id | order_date | item_id | quantity |
|---|---|---|---|---|
| 1 | 1 | 2020-06-01 | 10 | 5 |
| item_id | item_name | item_category |
|---|---|---|
| 10 | laptop | Electronics |
| item_category | Monday | Tuesday | Wednesday | Thursday | Friday | Saturday | Sunday |
|---|---|---|---|---|---|---|---|
| Electronics | 5 | 0 | 0 | 0 | 0 | 0 | 0 |
With only one order on Monday (June 1st, 2020) for Electronics category, all other days show 0 quantities. The cross join approach ensures all 7 days appear in the result.
Constraints
-
1 ≤ order_id ≤ 1000 -
1 ≤ customer_id ≤ 1000 -
order_dateis a valid date -
item_idis a non-empty string -
1 ≤ quantity ≤ 1000