Customer Order Aggregation
Beginner Mode
Objective
Write a SQL query that retrieves the names and email addresses of customers who have placed more than two orders. Additionally, for each customer, calculate the total number of orders they have placed and the total amount they have spent. The result should be sorted in descending order based on the total amount spent.
Additional Information
- The database consists of two tables:
customersandorders. - If a customer has not placed any orders, the total amount spent should be considered as 0.
- The output should include the following columns:
customer_name,email,total_orders, andtotal_spent. - The results should be sorted in descending order by
total_spent.
The customers table:
| Column | Type |
|---|---|
| id | integer |
| customer_name | string |
| string |
The orders table:
| Column | Type |
|---|---|
| id | integer |
| customer_id | integer |
| amount | decimal |
Examples
Example 1:
Output:
Input:
| customers | ||
|---|---|---|
| customer_name | id | |
| John Smith | [email protected] | 1 |
| Sarah Brown | [email protected] | 2 |
| Mike Johnson | [email protected] | 3 |
| Lisa Davis | [email protected] | 4 |
| orders | ||
|---|---|---|
| amount | customer_id | id |
| 100 | 1 | 1 |
| 150 | 1 | 2 |
| 200 | 1 | 3 |
| 300 | 2 | 4 |
| 250 | 2 | 5 |
| 175 | 3 | 6 |
| 400 | 2 | 7 |
| 120 | 4 | 8 |
| customer_name | total_orders | total_spent | |
|---|---|---|---|
| Sarah Brown | [email protected] | 3 | 950 |
| John Smith | [email protected] | 3 | 450 |
Code Environment
Sign in or try as guest to run your code.
Track
| Question | Difficulty | Company | Access |
|---|
Need more practice in this area? Explore more questions →
BMW