This will find the number of omissions of each student and will be sorted first with most paragraphs, as in your example.
SELECT studentname, count(absences_id) FROM Students s LEFT OUTER JOIN Absences a ON s.student_id=a.student_id GROUP BY studentname ORDER BY count(absences_id) DESC, student_name
LEFT OUTER JOIN is important because in some cases there are no rows in the absences table for some students. In this case, all fields from Absences for this row will be equal to zero, and the counter will be equal to zero, since it takes into account only non-zero fields.
If every absence can cover a date range, for example. absence due to sick leave or extended leave, then you should add start_date, end_date to the Absences table and replace COUNT (absens_id) with SUM (DATEDIFF (day, start_date, end_date)), for example
SELECT studentname, SUM(ISNULL(DATEDIFF(day, start_date, end_date),0) FROM Students s LEFT OUTER JOIN Absences a ON s.student_id=a.student_id GROUP BY studentname
You can set the ORDER BY clause to SUM (...), but this will improve readability and maintainability to wrap it in another query.
source share