Business Analytics · Problem 93 of 118

Teacher Reach

MediumBusiness AnalyticsSchool data

A teacher teaches the sections assigned to them. Return the teacher's name and students (the number of different students enrolled in any of their sections) for the five teachers with the most different students. Sort by students from high to low, then name.

Hint 1

teachers to sections to enrollments; a student in two sections of the same teacher counts once.

Reference solution

SELECT t.name, COUNT(DISTINCT e.student_id) AS students
FROM teachers AS t
JOIN sections AS s ON s.teacher_id = t.teacher_id
JOIN enrollments AS e ON e.section_id = s.section_id
GROUP BY t.teacher_id, t.name
ORDER BY students DESC, t.name
LIMIT 5;

After joining down a one-to-many-to-many path, the same student can appear several times under one teacher. COUNT(DISTINCT e.student_id) counts each student once. Before every join ask: "does this multiply my rows, and does my aggregate care?"