Subqueries and CTEs · Problem 62 of 118

Average Enrollments per Student

MediumSubqueries and CTEsSchool data

Return one row with avg_enrollments: the average, over the students who have at least one enrollment, of their number of enrollments, rounded to 2 decimals.

Hint 1

First count the enrollments per student. Then take the average of those counts. That is two levels of aggregation.

Reference solution

SELECT ROUND(AVG(n), 2) AS avg_enrollments
FROM (
  SELECT student_id, COUNT(*) AS n
  FROM enrollments
  GROUP BY student_id
) AS per_student;

You cannot nest aggregates (AVG(COUNT(*)) is an error), so compute the inner one in a derived table (a subquery in FROM, which needs an alias) and aggregate its result in the outer query. The second query answers a different question: the average over all students, including the 20 with no enrollment. Read the question carefully: "per enrolled student" and "per student" are different denominators.