按两列比较两个查询的最佳方法是什么?这些是我的表:
下表显示考试题
idEvaluation | Question | AllowMChoice | CorrectAnswer|
1 1 0 3
1 2 1 4
1 2 1 5
1 3 0 9
该表显示了已完成的考试
idExam| idEvaluation | Question | ChosenAnswer|
25 1 1 2
25 1 2 4
25 1 2 5
25 1 3 8
考虑到某些问题可能允许多项选择,我必须计算正确答案的百分比.
正确答案/总答案* 100
感谢您的提示!
解决方法:
此代码将向您显示问题列表以及是否正确回答了问题.
select
A.Question,
min(1) as QuestionsCount,
-- if this evaluates to null, they got A) the answer wrong or B) this portion of the answer wrong
-- we use MIN() here because we want to mark multi-answer questions as wrong if any part of the answer is wrong.
min(case when Q.idEvaluation IS NULL then 0 else 1 end) as QuestionsCorrect
from
ExamAnswers as A
left join ExamQuestions as Q on Q.Question = A.Question and Q.CorrectAnswer = A.ChosenAnswer
group by
A.Question -- We group by question to merge multi-answer-questions into 1
确认输出:
注意,这些列是故意用这种方式命名的,因为它们将作为子查询包含在下面的第2部分中.
此代码将为您提供测试成绩.
select
sum(I.QuestionsCorrect) as AnswersCorrect,
sum(I.QuestionsCount) as QuestionTotal,
convert(float,sum(I.QuestionsCorrect)) / sum(I.QuestionsCount) as PercentCorrect -- Note, not sure of the cast-to-float syntax for MySQL
from
(select
A.Eval,
A.Question,
min(1) as QuestionsCount,
min(case when Q.idEvaluation IS NULL then 0 else 1 end) as QuestionsCorrect
from
ExamAnswers as A
left join ExamQuestions as Q on Q.Question = A.Question and Q.CorrectAnswer = A.ChosenAnswer
where
A.Eval = 25
group by
A.Question, A.Eval) as I
group by
I.Eval
确认输出:
这将传达一般概念.我很难理解您的列名idEvaluation和Eval,但是我确信您可以根据需要调整上面的代码.
注意,我是在sql服务器中完成的,但是我使用了相当基本的SQL功能,因此它应该可以很好地转换成MySQL.