SQL query for quiz answers

SQL query for quiz answers

by Eduardo Rey -
Number of replies: 2

Hi,

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?

Thanks!

Average of ratings: -
In reply to Eduardo Rey

Re: SQL query for quiz answers

by Tim Hunt -
Picture of Core developers Picture of Documentation writers Picture of Particularly helpful Moodlers Picture of Peer reviewers Picture of Plugin developers

I think what is happening is that sometimes when the quiz is submitted, two question_attempt_steps are created, one to save the student's last answer, and then one to grade it.

In that case, the two steps will have the same timecreated. ORDER BY timecreated is not a reliable order.

Use ORDER BY sequencenumber.

I assume you already know of this bit of docs: https://docs.moodle.org/dev/Overview_of_the_Moodle_question_engine#Detailed_data_about_an_attempt

In reply to Tim Hunt

Re: SQL query for quiz answers

by Eduardo Rey -

Thanks a lot! I did  see that example query, but didn't figure out I to use the highest sequence number.