SELECT quiza.*, group_by_results.usertimeclose, group_by_results.usertimelimit FROM ( SELECT iquiza.id AS attemptid, quiz.course, quiz.graceperiod, COALESCE(quo.timeclose, MAX(qgo.timeclose), quiz.timeclose) AS usertimeclose, COALESCE(quo.timelimit, MAX(qgo.timelimit), quiz.timelimit) AS usertimelimit FROM mdl_quiz_attempts iquiza JOIN mdl_quiz quiz ON quiz.id = iquiza.quiz LEFT JOIN mdl_quiz_overrides quo ON quo.quiz = quiz.id AND quo.userid = iquiza.userid LEFT JOIN mdl_quiz_overrides qgo ON qgo.quiz = quiz.id LEFT JOIN mdl_groups_members gm ON gm.userid = iquiza.userid AND gm.groupid = qgo.groupid WHERE iquiza.state IN ('inprogress', 'overdue') AND iquiza.timemodified >= 0 AND iquiza.timemodified < now() GROUP BY iquiza.id, quiz.course, quiz.timeclose, quiz.timelimit, quiz.graceperiod, quo.timeclose, quo.timelimit ) group_by_results JOIN mdl_quiz_attempts quiza ON quiza.id = group_by_results.attemptid WHERE (state = 'inprogress' AND (now() > usertimeclose OR now() > quiza.timestart + usertimelimit)) OR (state = 'overdue' AND (now() > graceperiod + usertimeclose OR now() > graceperiod + quiza.timestart + usertimelimit)) ORDER BY course, quiz