31. 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.
Essential
SQL 0/33
Git 0/15
Spark 0/20
Snowflake 0/22
Python 0/24
Need more practice in this area? Explore more questions →
BMW
TCS
X
Accenture
Adobe
Google
LinkedIn
Samsung
Datadog
Wix
Dropbox
Meta
OpenAI
Hulu
Uber
DoorDash
Anthropic
Amazon
ActivisionBlizzard
Vercel
Crypto.Com
Zscaler
DeutscheBank
Apple
GoDaddy
PayPal
Snowflake
AMD
Twilio
Atlassian
JPMorgan
NVIDIA
IBM
Databricks
Coinbase
Cisco
Robinhood
Twitter
Microsoft
Palantir
Netflix
VMware
Cloudflare
Stripe
Capital One
Splunk
Intel
SAP
Tesla
GitHub
JaneStreet
Bloomberg
Salesforce
Elastic
CGI
UBS
GitLab
Ubisoft
Slack
Nintendo
EY
Kayak
Lyft
Airbnb
Walmart
Revolut
Visa
Okta
HashiCorp
Instacart
Mastercard