Find users with fewer than 3 orders or a total amount below 500, counted over all time. Return user_id, user_name, total_orders and total_spent for those users. Users with no orders are included with total_orders = 0 and total_spent = 0.
Input Table(s)
Table Users (primary key user_id):
| Column | Type | Meaning |
|---|
| user_id | INT | Id of the user. Primary key. |
| user_name | VARCHAR(100) | Name of the user. Not null. |
Table Orders (primary key order_id, foreign key user_id references Users.user_id):
| Column | Type | Meaning |
|---|
| order_id | INT | Id of the order. Primary key. |
| user_id | INT | User who placed the order. Foreign key to Users. |
| amount | DECIMAL(10,2) | Order amount. Not null, non-negative. |
| order_date | DATE | Date of the order. Not null. |
Output Contract
One row per qualifying user, with these columns in this order:
| Column | Meaning |
|---|
| user_id | Id of the user |
| user_name | Name of the user |
| total_orders | Number of the user's orders, 0 when the user has none |
| total_spent | Sum of amount over the user's orders, 0 when the user has none |
Order the result by user_id ascending. user_id is unique, so the order has no ties. total_spent is an exact sum of 2-decimal amounts, so no extra rounding is needed.
Example
Users:
| user_id | user_name |
|---|
| 1 | Alice |
| 2 | Bob |
| 3 | Chen |
| 4 | Dana |
| 5 | Eli |
Orders:
| order_id | user_id | amount | order_date |
|---|
| 101 | 1 | 200.00 | 2024-01-05 |
| 102 | 1 | 150.00 | 2024-02-10 |
| 103 | 1 | 300.00 | 2024-03-15 |
| 104 | 2 | 400.00 | 2024-01-20 |
| 105 | 2 | 350.00 | 2024-04-02 |
| 106 | 3 | 100.00 | 2024-01-08 |
| 107 | 3 | 120.00 | 2024-02-14 |
| 108 | 3 | 130.00 | 2024-03-01 |
| 109 | 3 | 140.00 | 2024-03-22 |
| 110 | 5 | 250.00 | 2024-02-01 |
| 111 | 5 | 125.00 | 2024-02-15 |
| 112 | 5 | 125.00 | 2024-03-05 |
Expected result:
| user_id | user_name | total_orders | total_spent |
|---|
| 2 | Bob | 2 | 750.00 |
| 3 | Chen | 4 | 490.00 |
| 4 | Dana | 0 | 0.00 |
Bob qualifies on order count (2) even though he spent 750. Chen has 4 orders but a total of 490. Dana has no orders, so both totals are 0. Alice (3 orders, 650) and Eli (3 orders, exactly 500) meet neither condition.
Constraints and Clarifications
-
1 to 10,000 users, and 0 to 1,000 orders per user.
-
amount
is non-negative and never NULL.
-
Both thresholds are strict. Exactly 3 orders or a total of exactly 500 does not qualify by itself.
-
A user qualifies when either condition holds.
-
"All time" means there is no date filter;
order_date
is not needed.
-
Two users can share a
user_name
; they are still separate users.
-
An order with a NULL
user_id
belongs to no user and is not counted.