我正在制作一个"测验应用程序"。每个测验都有多个问题(quizComponents),每个问题都有多个答案选项(quizComponentOptions)供参与者选择。答案保存在quizResults表中。我有这些表:
我想获得所有测验的列表,每个测验中包含总数,以及每个测验中任何给定personId的正确/不正确答案的数量。 类似的东西:
quizTitle total_quiz_components correct_answers incorrect_answers
"Quiz 1" 3 2 1
"Quiz 2" 10 1 9
以下查询为我提供了测验中的所有行,每个测验包含的测验组件总数。
SELECT q.quizTitle, count(qc.componentId) AS total_quiz_components FROM Quiz q
LEFT JOIN QuizComponents qc ON qc.quizId=q.quizId
GROUP BY q.quizId;
但后来我陷入了这种疯狂的关系中。
答案 0 :(得分:2)
您需要case based aggregation
才能获得正确且错误的答案。
SELECT q.quizTitle,
count(qc.componentId) AS total_quiz_components ,
sum ( case when CO.optionId = QR.answerOptionId then 1 else 0 end) as correct_answers,
sum ( case when CO.optionId <> QR.answerOptionId then 1 else 0 end) as incorrect_answers,
FROM Quiz q
LEFT JOIN QuizComponents qc ON qc.quizId=q.quizId
LEFT JOIN QuizResults QR on
QR.componentId = QC.componentId
LEFT JOIN CorrectOptions CO
on CO.componentId = QR.componentId
GROUP BY q.quizTitle;