Given a table Orders containing order information, write a SQL solution to find the number of unique orders and the number of unique customers with invoices greater than $20 for each different month.
The table structure is:
order_id: Unique identifier for each orderorder_date: Date when the order was placedcustomer_id: ID of the customer who placed the orderinvoice: Invoice amount for the order
Return the result table showing monthly statistics, sorted in any order.
Table Schema
| Column Name | Type | Description |
|---|---|---|
order_id
PK
|
int | Unique identifier for each order |
order_date
|
date | Date when the order was placed |
customer_id
|
int | ID of the customer who placed the order |
invoice
|
int | Invoice amount in dollars |
Input & Output
| order_id | order_date | customer_id | invoice |
|---|---|---|---|
| 1 | 2021-01-01 | 1 | 30 |
| 2 | 2021-01-02 | 2 | 40 |
| 3 | 2021-01-03 | 3 | 70 |
| 4 | 2021-02-07 | 1 | 30 |
| 5 | 2021-02-09 | 4 | 80 |
| month | order_count | customer_count |
|---|---|---|
| 2021-01-01 | 3 | 3 |
| 2021-02-01 | 2 | 2 |
In January 2021, there are 3 unique orders (1, 2, 3) from 3 unique customers (1, 2, 3) with invoices > 20. In February 2021, there are 2 unique orders (4, 5) from 2 unique customers (1, 4) with invoices > 20.
| order_id | order_date | customer_id | invoice |
|---|---|---|---|
| 1 | 2021-01-01 | 1 | 30 |
| 2 | 2021-01-02 | 2 | 15 |
| 3 | 2021-01-03 | 3 | 25 |
| month | order_count | customer_count |
|---|---|---|
| 2021-01-01 | 2 | 2 |
Only orders with invoice > 20 are counted. Order 2 with invoice $15 is filtered out, so only orders 1 and 3 from customers 1 and 3 are included in the January count.
| order_id | order_date | customer_id | invoice |
|---|---|---|---|
| 1 | 2021-01-01 | 1 | 30 |
| 2 | 2021-01-15 | 1 | 25 |
| 3 | 2021-01-20 | 2 | 40 |
| month | order_count | customer_count |
|---|---|---|
| 2021-01-01 | 3 | 2 |
Customer 1 has 2 different orders in January, so order_count is 3 (all unique orders) but customer_count is 2 (customers 1 and 2, with customer 1 counted only once despite multiple orders).
Constraints
-
1 ≤ order_id ≤ 10^6 -
order_dateis a valid date -
1 ≤ customer_id ≤ 10^6 -
1 ≤ invoice ≤ 10^6