Ravindra BagaleCourses & study guides Track your progress

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

  1. Run the first example to read every branch target and currency.
  2. Run the second example to check Mumbai months against 9,00,000 rupees.
  3. Run the third example to list accounts with 4 or more transactions and their total amount.
  4. 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_idbranch_namecurrencymonthly_target
1Northstar London BridgeGBP30000
2Northstar ManhattanUSD40000
3Northstar FortINR900000
4Northstar FC RoadINR600000

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

monthtotal_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_idtransactionstotal_amount
103451700.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.