18. Subquery for Best Order per Customer
Beginner Mode
Objective
Given two tables, customers and orders, write an SQL query to retrieve each customer's name along with the ID and total amount of their highest-value order. The results should be ordered alphabetically by the customer's name.
Additional information
- Each customer may have multiple orders.
- If a customer has multiple orders with the same highest total amount, return the order with the smallest
order_id.
The customers table:
| Column | Type | Description |
|---|---|---|
| customer_id | integer | Unique identifier for each customer |
| customer_name | string | Name of the customer |
The orders table:
| Column | Type | Description |
|---|---|---|
| order_id | integer | Unique identifier for each order |
| customer_id | integer | Identifier linking the order to a customer |
| total_amount | decimal | Total amount of the order |
- Ensure that all customers with at least one order are included in the result.
- Order the final output by
customer_namein ascending order.
Examples
Example 1:
Output:
Input:
| customers | |
|---|---|
| customer_id | customer_name |
| 1 | Alice Smith |
| 2 | Bob Johnson |
| 3 | Carol White |
| orders | ||
|---|---|---|
| customer_id | order_id | total_amount |
| 1 | 1 | 150 |
| 1 | 2 | 300 |
| 2 | 3 | 450 |
| 2 | 4 | 200 |
| 3 | 5 | 500 |
| 3 | 6 | 175 |
| customer_name | order_id | total_amount |
|---|---|---|
| Alice Smith | 2 | 300 |
| Bob Johnson | 3 | 450 |
| Carol White | 5 | 500 |
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 →
Anthropic
TCS
X
Accenture
Adobe
Google
LinkedIn
Samsung
Datadog
Wix
Dropbox
Meta
OpenAI
Hulu
Uber
DoorDash
Amazon
ActivisionBlizzard
Vercel
Crypto.Com
Zscaler
DeutscheBank
Apple
GoDaddy
BMW
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