按两列比较两个查询的最佳方法是什么?这些是我的表:
此表显示试题
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 server 中执行此操作,但我使用了相当基本的 SQL 功能,因此它应该可以很好地转换为 MySQL。
关于mysql - 如何在 MySQL 中按两列比较两个查询?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6345128/