Aggregation and Grouping · Problem 32 of 118

Graded versus Enrolled

MediumAggregation and GroupingSchool data

For section_id from 1 to 5, return section_id, enrolled (number of enrollments), graded (number with a grade) and average_grade (the average grade rounded to 1 decimal). Sort by section_id.

Hint 1

COUNT(*) counts every row, COUNT(grade) only the rows where the grade is not NULL.

Hint 2

AVG ignores NULL values by itself.

Reference solution

SELECT section_id,
       COUNT(*) AS enrolled,
       COUNT(grade) AS graded,
       ROUND(AVG(grade), 1) AS average_grade
FROM enrollments
WHERE section_id BETWEEN 1 AND 5
GROUP BY section_id
ORDER BY section_id;

Aggregate functions skip NULL (only COUNT(*) counts every row). That is usually what you want: a student without a grade has no grade, not a grade of zero. Turning NULL into 0 with COALESCE would pull the average down and give a wrong answer to "what is the average grade?". Choose deliberately whether "missing" means "unknown" or "zero".