Aggregation and Grouping · Problem 40 of 118

Students with the Most Absences

HardAggregation and GroupingSchool data

Return student_id and absences (the number of attendance rows with status = 'absent') for the three students with the most absences. Sort by absences from high to low, then by student_id.

Several students have the same number of absences, so the tie-breaker decides who is in the top three.

Hint 1

Filter the absences with WHERE, group by student, count, sort, limit.

Reference solution

SELECT student_id, COUNT(*) AS absences
FROM attendance
WHERE status = 'absent'
GROUP BY student_id
ORDER BY absences DESC, student_id
LIMIT 3;

"Top N" queries need a complete sort order. Five students tie with the maximum number of absences, so LIMIT 3 must cut through the tie: without a tie-breaker the three you get could differ between runs, between databases, or after the table is reorganised. student_id makes the choice deterministic. Ask yourself each time: "if two rows tie, which one should win?"