【问题标题】:How do I compare two queries by two columns in MySQL?如何在 MySQL 中按两列比较两个查询?
【发布时间】:2011-06-14 14:27:57
【问题描述】:

按两列比较两个查询的最佳方法是什么?这些是我的桌子:

此表显示考试题目

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

感谢您的提示!

【问题讨论】:

  • 如果选择了所有正确选项,或者选择了任何正确选项,多选答案是否正确? (所以在您的问题 2 示例中,(4,5)是 1 个正确答案还是 2,并且(3,5)会被视为一个正确答案(因为 5 是正确的)?
  • 如果选择了所有正确选项,则多选答案是正确的

标签: mysql sql count compare


【解决方案1】:

此代码将向您显示问题列表以及是否正确回答。

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

输出确认:

这将传达一般概念。我很难理解您的列名idEvaluationEval,但我相信您可以调整上面的代码以满足您的目的。

注意,我是在 sql server 中完成的,但我使用了相当基本的 SQL 功能,所以它应该可以很好地转换为 MySQL。

【讨论】:

  • eval 被编辑为 idExam,这是一个已经完成的考试。 idEvaluation 只是每个考试的主键。感谢您的提示,我将对此进行测试。
  • min(当 Q.idEvaluation 为 NULL 然后 0 否则 1 结束的情况)作为 QuestionsCorrect。我看不懂这段代码,idEvaluation 不能为 NULL,因为是指向考试的 FK
  • 检查ON Clause - 它加入 Q.Question = A.Question ALSO 上 Q.CorrectAnswer = A.ChosenAnswer;因此,当 On 子句不评估为真时,Q.idEvaluation 将为 NULL。这就是我检查是否有正确答案的方式,它适用于多项选择题或常规问题。
猜你喜欢
  • 1970-01-01
  • 2011-04-15
  • 1970-01-01
  • 2013-03-03
  • 1970-01-01
  • 2011-10-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多