The Number of Rich Customers - Problem
You're working as a data analyst for a luxury retail store and need to identify your VIP customers who make high-value purchases. Your task is to analyze the store's billing database and count how many unique customers have made at least one purchase exceeding $500.
Given a Store table with the following structure:
| Column Name | Type |
|---|---|
| bill_id | int |
| customer_id | int |
| amount | int |
Where:
bill_idis the primary key (unique identifier for each bill)customer_ididentifies which customer made the purchaseamountrepresents the bill amount in dollars
Goal: Write a SQL query to count the number of distinct customers who have at least one bill with an amount strictly greater than 500.
Note: A customer might have multiple bills, but we only count them once if they qualify as a "rich customer".
Input & Output
example_1.sql โ Basic Case
$
Input:
Store table:
| bill_id | customer_id | amount |
|---------|-------------|--------|
| 1 | 1 | 200 |
| 2 | 2 | 800 |
| 3 | 3 | 450 |
| 4 | 4 | 600 |
| 5 | 2 | 300 |
| 6 | 1 | 750 |
โบ
Output:
| rich_count |
|------------|
| 3 |
๐ก Note:
Customers 1, 2, and 4 have at least one bill > $500. Customer 1 has bill of $750, customer 2 has bill of $800, and customer 4 has bill of $600. Customer 3 only has $450 bill, so they don't qualify.
example_2.sql โ All Poor Customers
$
Input:
Store table:
| bill_id | customer_id | amount |
|---------|-------------|--------|
| 1 | 1 | 200 |
| 2 | 2 | 300 |
| 3 | 3 | 450 |
| 4 | 1 | 500 |
โบ
Output:
| rich_count |
|------------|
| 0 |
๐ก Note:
No customer has any bill with amount strictly greater than 500. Customer 1's highest bill is exactly $500, which doesn't qualify (must be > 500, not >= 500).
example_3.sql โ Single Rich Customer
$
Input:
Store table:
| bill_id | customer_id | amount |
|---------|-------------|--------|
| 1 | 1 | 501 |
| 2 | 1 | 200 |
| 3 | 1 | 100 |
โบ
Output:
| rich_count |
|------------|
| 1 |
๐ก Note:
Only customer 1 exists and they have one bill of $501 which exceeds $500, so they qualify as a rich customer. Multiple bills from the same customer still count as one rich customer.
Constraints
- 1 โค bill_id โค 105
- 1 โค customer_id โค 104
- 1 โค amount โค 106
- bill_id is unique (primary key)
- All values are positive integers
Visualization
Tap to expand
Understanding the Visualization
1
Scan All Bills
Go through each bill in the Store table
2
Filter High Amounts
Keep only bills with amount > $500
3
Track Unique Customers
Use hash table to remember distinct customer IDs
4
Count VIP Customers
Return the count of unique customers who qualify
Key Takeaway
๐ฏ Key Insight: SQL's COUNT(DISTINCT) with WHERE clause is the perfect tool for counting unique entities that meet a condition - exactly what we need for identifying VIP customers!
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code