Ravindra BagaleCourses & study guides Track your progress

13. HAVING: Filter Groups After Aggregates

13.2 How to Keep Groups with HAVING SUM(amount) Above a Target

Why. A regional head wants to see only the months when a branch crossed a target, not every month.

What. HAVING SUM(amount) > number keeps only the groups whose total is above that number. Keep currencies apart: compare Indian branches with a rupee target and the London branch with a pound target.

How. Group the Mumbai and Pune rows by branch and month, then keep only the groups above 1,00,000 rupees.

Steps

  1. Run the first example and read which branch months crossed 1,00,000 rupees.
  2. Run the second example for London with a target of 5,000 pounds.
  3. Notice that each query looks at one currency only.
  4. Change the target number and run again to see more or fewer groups.

Examples

Example 1 · dataset: northstar_bank

SELECT branch_id,
       strftime('%Y-%m', posted_at) AS month,
       SUM(amount)                  AS total_inr
FROM transactions
WHERE branch_id IN (3, 4)
GROUP BY branch_id, month
HAVING SUM(amount) > 100000
ORDER BY branch_id, month;

Output

branch_idmonthtotal_inr
32026-08192000.0
32026-09276000.0
32026-10657000.0
42026-09166000.0

Meaning. Only the branch months above 1,00,000 rupees remain. Pune in August and October stay out, because their totals are below that target.

Example 2 · dataset: northstar_bank

SELECT strftime('%Y-%m', posted_at) AS month,
       SUM(amount)                  AS total_gbp
FROM transactions
WHERE branch_id = 1
GROUP BY month
HAVING SUM(amount) > 5000
ORDER BY month;

Output

monthtotal_gbp
2026-107950.0

Meaning. For London, August and September stay below 5,000 pounds. Only October crosses the target, with 7,950 pounds.

Ravindra Bagale's Tip

SQLite lets you write HAVING total_inr > 100000 with the alias, but many other databases do not. Writing the full SUM(amount) works everywhere.