Final challenge: the course report
After this: Read, complete and fix join queries that build a report of the school.
The school office wants a report: every course, with its teacher and its number of students, Music included. Then two questions that need more tables: who does Mr Silva teach, and how many credits does each student carry? This challenge has five steps, and each step is scored on its own. You will read the report, complete its missing join, follow a query across four tables, add up credits per student, and find out who that last query leaves out. You can try as many times as you like, and hints work as they do in the lessons.
Each course with its teacher and its number of students, most students first. Where does Music appear, and with what count?
SELECT c.title, t.name, COUNT(e.student_id) AS studentsFROM courses AS cJOIN teachers AS t ON t.id = c.teacher_idLEFT JOIN enrolments AS e ON e.course_id = c.idGROUP BY c.id, c.title, t.nameORDER BY students DESC, c.title;Write the missing line, so that the report counts each course's students and still lists Music with 0. Use the short name e for enrolments.
SELECT c.title, t.name, COUNT(e.student_id) AS studentsFROM courses AS cJOIN teachers AS t ON t.id = c.teacher_id______________ -- ← the missing lineGROUP BY c.id, c.title, t.nameORDER BY students DESC, c.title;Who does Mr Silva teach, and in which course? This query goes from teachers to students through two other tables.
SELECT s.name, c.titleFROM teachers AS tJOIN courses AS c ON c.teacher_id = t.idJOIN enrolments AS e ON e.course_id = c.idJOIN students AS s ON s.id = e.student_idWHERE t.name = 'Mr Silva'ORDER BY s.name;Each student's total credits, highest first. What are the first two rows?
SELECT s.name, SUM(c.credits) AS creditsFROM students AS sJOIN enrolments AS e ON e.student_id = s.idJOIN courses AS c ON c.id = e.course_idGROUP BY s.id, s.nameORDER BY credits DESC, s.name;The credits query above gives five rows. The school has six students. Who is missing, and how would you keep them?
Every query in the challenge runs on the same school tables as the lessons. The playground has the course report ready to change: add the teacher, sort it another way, or try one of the three mistakes from lesson 5 and watch the numbers go wrong.
- Read a course report built with a JOIN and a LEFT JOIN, complete its missing join, follow a query across four tables, add up credits per student, and say who a plain join leaves out.