Bank Account Summary II - Problem
You're working as a database analyst for a major bank that needs to identify high-balance customers for their premium banking services.
Given two database tables:
- Users: Contains account numbers and customer names
- Transactions: Contains all financial transactions (deposits are positive, withdrawals are negative)
Your task is to calculate each customer's current balance by summing all their transactions, then identify customers with balances exceeding $10,000.
All accounts start with a balance of 0, and you need to return the name and balance of qualifying customers.
This is a classic SQL aggregation problem that tests your ability to join tables and perform GROUP BY operations with filtering.
Input & Output
example_1.sql โ Basic Example
$
Input:
Users: [(1,'Noah'), (2,'Mila')]
Transactions: [(1,1,2000,'2020-01-01'), (2,1,3000,'2020-02-01'), (3,2,-1000,'2020-03-01'), (4,1,1000,'2020-04-01'), (5,2,15000,'2020-05-01')]
โบ
Output:
[('Mila', 14000)]
๐ก Note:
Noah's balance: 2000 + 3000 + 1000 = 6000 (below threshold). Mila's balance: -1000 + 15000 = 14000 (above 10000).
example_2.sql โ Multiple High Balances
$
Input:
Users: [(1,'Alice'), (2,'Bob'), (3,'Charlie')]
Transactions: [(1,1,12000,'2020-01-01'), (2,2,11000,'2020-02-01'), (3,3,5000,'2020-03-01')]
โบ
Output:
[('Alice', 12000), ('Bob', 11000)]
๐ก Note:
Alice: 12000 (qualifying), Bob: 11000 (qualifying), Charlie: 5000 (below threshold).
example_3.sql โ Edge Case with Negative Balance
$
Input:
Users: [(1,'David'), (2,'Emma')]
Transactions: [(1,1,20000,'2020-01-01'), (2,1,-25000,'2020-02-01'), (3,2,15000,'2020-03-01')]
โบ
Output:
[('Emma', 15000)]
๐ก Note:
David's balance: 20000 - 25000 = -5000 (negative, below threshold). Emma's balance: 15000 (above threshold).
Visualization
Tap to expand
Understanding the Visualization
1
Join Customer Data
Connect Users table with Transactions table using account number
2
Group by Account
Group all transactions belonging to each customer
3
Calculate Balances
Sum up all transaction amounts for each customer
4
Filter High Balances
Select only customers with balances exceeding $10,000
Key Takeaway
๐ฏ Key Insight: Using JOIN with GROUP BY allows SQL to efficiently aggregate data in a single pass, avoiding expensive subqueries and delivering optimal performance for balance calculations.
Time & Space Complexity
Time Complexity
O(n + m)
Single scan of users (n) and transactions (m) with efficient grouping
โ Linear Growth
Space Complexity
O(k)
Space for k unique accounts in GROUP BY operation
โ Linear Space
Constraints
- 1 โค Users.account, Transactions.account โค 105
- 1 โค Transactions.trans_id โค 106
- -106 โค Transactions.amount โค 106
- All account numbers in Transactions exist in Users table
- User names are unique and contain only letters
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code