13. HAVING: Filter Groups After Aggregates
13.4 Practice: Branches Above Target and Busy Accounts Only
Why. This practice answers two questions a bank manager asks every month: which branch months beat the target, and which accounts are very busy.
What. Each branch has its own monthly_target in the branches table. You read the target first, and then use it in HAVING for that branch. Busy accounts are accounts with 4 or more transactions.
How. Look up the targets, then check Mumbai against its target of 9,00,000 rupees, then list busy accounts.
Steps
- Run the first example to read every branch target and currency.
- Run the second example to check Mumbai months against 9,00,000 rupees.
- Run the third example to list accounts with 4 or more transactions and their total amount.
- Write down which months and accounts you would show the manager.
Examples
Example 1 · dataset: northstar_bank
SELECT branch_id, branch_name, currency, monthly_target
FROM branches
ORDER BY branch_id;Output
| branch_id | branch_name | currency | monthly_target |
|---|---|---|---|
| 1 | Northstar London Bridge | GBP | 30000 |
| 2 | Northstar Manhattan | USD | 40000 |
| 3 | Northstar Fort | INR | 900000 |
| 4 | Northstar FC Road | INR | 600000 |
Meaning. Each branch has a target in its own currency. Mumbai's target is 9,00,000 rupees a month.
Example 2 · dataset: northstar_bank
SELECT strftime('%Y-%m', posted_at) AS month,
SUM(amount) AS total_inr
FROM transactions
WHERE branch_id = 3
GROUP BY month
HAVING SUM(amount) > 900000
ORDER BY month;Output
| month | total_inr |
|---|
Meaning. No row comes back, which means Mumbai did not cross its 9,00,000 rupee target in any month. An empty result is also an answer.
Example 3 · dataset: northstar_bank
SELECT account_id,
COUNT(*) AS transactions,
SUM(amount) AS total_amount
FROM transactions
GROUP BY account_id
HAVING COUNT(*) >= 4
ORDER BY transactions DESC, account_id;Output
| account_id | transactions | total_amount |
|---|---|---|
| 103 | 4 | 51700.0 |
Meaning. Only account 103, Grace Miller in New York, has 4 or more transactions. Her total of 51,700 is in US dollars, her branch currency.
Ravindra Bagale's Tip
When a HAVING query returns no rows, check the target and the currency before you assume the query is wrong.
Ravindra Bagale's Tip – मराठी
HAVING query एकही row देत नसेल, तर query चुकली असं समजण्याआधी target आणि currency तपासा.
Ravindra Bagale's Tip – हिंदी
HAVING query कोई row न दे, तो query गलत है यह मानने से पहले target और currency जाँचिए।