如何在MySQL中将两个查询比较两列?

时间:2011-06-14 14:27:58

标签: mysql sql count compare

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

此表显示考题

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

感谢您的提示!

1 个答案:

答案 0 :(得分:3)

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

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

输出已确认:

enter image description here

请注意,这些列是以这种方式有意命名的,因为它们将作为子查询包含在下面的第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

输出已确认:

enter image description here

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

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