CodingNeed.

3 · Summarize and connect · 12 MIN

Build a grouped report and filter groups

GROUP BY changes the result grain from one learner to one city.

A report’s grain tells you what one output row represents. Grouping by city creates one output row per city value, including one NULL group. COUNT(*) and SUM(points) are calculated separately inside each group. WHERE filters individual rows before grouping; HAVING filters the resulting groups. Do not select a learner name while grouping only by city: one city can contain several names and there is no single correct name for that output row.

Keep the source rows visible. Predict which rows and columns will remain after each operation.

Before you start

No installation. The tables below are loaded automatically for every run; edits do not touch the CodingNeed account database.

New words, explained

grain
What a single result row represents.
GROUPBY
Form groups sharing selected values.
HAVING
Filter groups after aggregate values are available.

Follow the example step by step

  1. Write the target grain: one row per city.
  2. Place Ada and Grace in the same Delhi group.
  3. Aggregate each group, then apply HAVING.
  4. Exclude missing cities with WHERE before grouping in the exercise.
Practice table: learners
idnamecitypoints
1AdaDelhi20
2LinNULL (unknown)0
3GraceDelhi35
4SamPune20
Practice table: enrollments
learner_idcourse
1React
1SQL
3SQL

You are ready to move on when: Return city and SUM(points) for known cities only. Keep groups totaling at least 30 points, and order by city.

Read the example

SELECT COALESCE(city, 'Unknown'), COUNT(*), SUM(points)
FROM learners
GROUP BY city
ORDER BY COALESCE(city, 'Unknown');
Check the expected output
[["Delhi",2,55],["Pune",1,20],["Unknown",1,0]]

Your challenge

Return city and SUM(points) for known cities only. Keep groups totaling at least 30 points, and order by city.

Common trap

Putting an aggregate condition in WHERE confuses row filtering with group filtering.

Further reading: SQLite SELECT reference

Next lesson: Project · Join learners to enrollment counts

Essential cookies keep your account signed in. Optional analytics is not configured on this site. Your choice does not affect access to lessons.

Read the Privacy Policy. You can change this choice in the footer.