Aggregation & GROUP BY

COUNT variants, GROUP BY, HAVING and conditional sums

40 min · interactive lesson with runnable code and 6 graded exercises.

What you'll be able to do

  • Explain why COUNT(*), COUNT(col) and COUNT(DISTINCT col) differ
  • Group rows and compute per-segment metrics
  • Use WHERE before and HAVING after grouping
  • Pivot with conditional aggregation and compute rates safely

Aggregate functions

Many rows in, one number out

Three kinds of COUNT

Rows, values, distinct values

GROUP BY

One row per segment

GROUP BY collapses rows that share a value into one output row. Every column in SELECT must be either grouped or aggregated.

WHERE vs HAVING

Before vs after grouping

WHERE filters rows before they are grouped. HAVING filters groups after aggregation, so it can use COUNT, SUM, …

Conditional aggregation

Pivot with SUM(CASE …)

Put a CASE inside an aggregate to count or sum only some rows. This is how you build a pivot table in SQL — one row per segment, one column per condition.

Rates without bugs

Numerator, denominator, 100.0

For a 0/1 column, AVG is the rate: AVG(churned) = share churned. And always say what the denominator is — all customers? only active ones? only those who answered?