10 / 10

GROUP BY & Aggregates

Compute counts and sums; HAVING for post-aggregate filters.

What you’ll learn

  • Aggregate rows and filter post-aggregation with HAVING.
SELECT CustomerID,
       COUNT(*)      AS Orders,
       SUM(TotalDue) AS Revenue
FROM dbo.Sales
GROUP BY CustomerID
HAVING SUM(TotalDue) > 1000;

Notes

  • Every non-aggregated select column must appear in GROUP BY.
  • Use GROUP BY ROLLUP(...) or GROUPING SETS for subtotals.