I created a query to get the answers for each question from the highest scored attempt for each student:
select u.username, question.name, case when qas.state = "gradedright" or qas.fraction = qatt.maxmark then 1 else 0 end correct FROM mdl_quiz AS q JOIN mdl_course_modules AS cm ON cm.instance = q.id JOIN mdl_quiz_attempts qa ON q.id = qa.quiz and qa.id = ( select id from mdl_quiz_attempts where quiz = q.id and userid = u.id ORDER BY sumgrades DESC LIMIT 1 ) JOIN mdl_user AS u ON u.id = qa.userid JOIN mdl_question_usages AS qu ON qu.id = qa.uniqueid JOIN mdl_question_attempts AS qatt ON qatt.questionusageid = qu.id JOIN mdl_question AS question ON question.id = qatt.questionid JOIN mdl_question_attempt_steps AS qas ON qas.questionattemptid = qatt.id and qas.id = ( SELECT sortqas.id FROM mdl_question_attempt_steps sortqas WHERE sortqas.questionattemptid = qatt.id ORDER BY sortqas.timecreated DESC LIMIT 1 ) JOIN mdl_course crs on crs.id = cm.course WHERE cm.id = ?
However, it seems some of the correct answers are registered with mdl_question_attempt_steps.state = "completed" instead of "gradedright", so I considered mdl_question_attempt_steps.fraction = mdl_question_attempts.fraction as correct answers as well.
Can someone please tell me if this is a consistent consideration or if it has any issues like precision differences or whatever? Also, is there a better way to determine correct answers?