For each customer, sum order_cost for orders in the last 30 days relative to the fixed reference date 2024-03-31 (order_date between 2024-03-01 and 2024-03-31, inclusive). Return customer_id, customer_name and total_recent_cost, only for customers with at least one qualifying order.
Input Table(s)
customers
| Column | Type | Meaning |
|---|
| customer_id | INT | Unique id of the customer |
| customer_name | VARCHAR(100) | Customer's name, NOT NULL |
Primary key: customer_id.
orders
| Column | Type | Meaning |
|---|
| order_id | INT | Unique id of the order |
| customer_id | INT | Customer who placed the order, references customers.customer_id |
| order_date | DATE | Date the order was placed, NOT NULL |
| order_cost | DECIMAL(10,2) | Cost of the order, NOT NULL |
Primary key: order_id. Foreign key: customer_id references customers(customer_id).
Output Contract
Return the columns customer_id, customer_name, total_recent_cost, in that order, one row per customer with at least one qualifying order. total_recent_cost is the exact sum of order_cost over the qualifying orders, with two decimal places and no further rounding. Sort by total_recent_cost descending, then customer_id ascending.
Example
Input customers:
| customer_id | customer_name |
|---|
| 1 | Alice |
| 2 | Bob |
| 3 | Chen |
| 4 | Dana |
| 5 | Eli |
Input orders:
| order_id | customer_id | order_date | order_cost |
|---|
| 101 | 1 | 2024-03-05 | 120.00 |
| 102 | 1 | 2024-02-29 | 300.00 |
| 103 | 2 | 2024-03-31 | 80.00 |
| 104 | 2 | 2024-03-01 | 40.00 |
| 105 | 3 | 2024-03-15 | 0.00 |
| 106 | 4 | 2024-04-01 | 50.00 |
| 107 | 5 | 2024-03-20 | 75.50 |
Expected output:
| customer_id | customer_name | total_recent_cost |
|---|
| 1 | Alice | 120.00 |
| 2 | Bob | 120.00 |
| 5 | Eli | 75.50 |
| 3 | Chen | 0.00 |
Order 102 falls before the window, so Alice's total is 120.00. Bob's two orders sit on the two boundary dates and both count, giving 120.00, and the tie with Alice is broken by customer_id. Chen's only order costs 0.00 and is inside the window, so Chen is returned with 0.00. Dana's only order is after the window, so Dana is left out.
Constraints and Clarifications
-
The
customers
table has 1 to
104
rows and the
orders
table has 1 to
105
rows.
-
order_cost
is non-negative with up to two decimal places. An order that costs 0.00 still counts as a qualifying order.
-
order_id
is unique, and every
customer_id
in
orders
exists in
customers
.
-
Both ends of the window are inclusive: orders dated 2024-03-01 and 2024-03-31 count, orders dated 2024-02-29 or 2024-04-01 do not. Use the fixed reference date, not the current date.
-
Customers with no qualifying order do not appear in the output.
-
customer_name
may repeat across customers.
customer_id
identifies a customer.