mysql - 如何在 MySQL 中按两列比较两个查询?

标签 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

感谢您的提示!

最佳答案

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

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。

关于mysql - 如何在 MySQL 中按两列比较两个查询?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6345128/

相关文章:

MySQL 查询 SELECT FROM 2 个表,COUNT 最常用

count - Netlogo 计数链接

javascript - 在从 PHP 生成的 javascript 对象中转义引号

MySQL:使用 Union 将多个 Select 查询拆分到各自的表中

php - 如何在单个 sql 查询中处理多对多关系?

SQL - 如何选择单词末尾具有某些值的单词

mysql - 如何在不编写与子查询相同的查询的情况下在 WHERE 子句中使用实际行数 (COUNT(*))?

mysql - 如何优化我的 mysql 查询?

PHP分解数据并显示在表格中

MySQL日期转换("30-Jan-2013"到 "2013-01-28")