HAVING, subqueries and finance calculations
Filter calculated metrics and build analytical queries.
Advanced
SQL syntax
Finance and accounting scenario
Related exercises
Objective
Filter after aggregation, use subqueries and build metrics such as net VAT payable, margin rate or customer exposure.
Exercise context
These exercises introduce combined calculations: VAT collected minus deductible VAT, margin divided by revenue, or customers above an exposure threshold.
Key concepts
- WHERE filters rows before calculation.
- HAVING filters groups after calculation.
- A subquery makes a calculated result available to another query.
- ROUND rounds a ratio.
- Metrics should use explicit aliases.
Syntax pattern
SELECT groupe, SUM(montant) AS total
FROM table
GROUP BY groupe
HAVING SUM(montant) > seuil;
Applied example
SELECT
(SELECT SUM(tva) FROM factures) -
(SELECT SUM(tva_deductible) FROM factures_achats) AS tva_a_decaisser;
Common mistakes
- Using WHERE on an aggregated metric.
- Forgetting parentheses in a subquery.
- Creating a ratio without handling the denominator.
- Not rounding a financial rate.