多选答案T-SQL查询

时间:2017-04-15 08:20:31

标签: sql sql-server sql-server-2008 tsql

查询是为了获取用户是否为问题选择了多项选择答案是否正确,如果正确则为1,否则为0

我有两个表question_answeruser_exam_answer,条目表的用户在submitted_option_id列中提交了答案

user_exam_answer table

question_answer

当用户回答(user_exam_answer)与问题回答(question_answer)表

匹配时,我尝试编写查询
select 
    count(1) as result 
from 
    (select 
         qa.question_id, 
         count(qa.correct_option_id) as col1, 
         count(sa.submited_option_id) as col2 
     from 
         question_answer qa
     left join 
         user_exam_answers sa on (sa.question_id = qa.question_id 
                                  and sa.submited_option_id = qa.correct_option_id 
                                  and sa.exam_id = 'html_001' 
                                  and sa.user_id = 'user_123')
     group by 
         qa.question_id
     having 
         count(qa.correct_option_id) = count(sa.submited_option_id) 
 ) as t

但问题出在:

  • QA(question_answer.correct_option_id)有3个条目,SA user_exam_answers.submited_option_id有2个条目,然后查询正确并返回

  • QA(question_answer.correct_option_id)有2个条目,SA(user_exam_answers.submited_option_id)是3个条目,然后查询正确并返回

  • QA(question_answer.correct_option_id)有2个条目SA(user_exam_answers.submited_option_id)有1个条目,然后查询正确并返回

  • QA(question_answer.correct_option_id)有1个条目,SA(user_exam_answers.submited_option_id)有2个条目,然后查询返回错误答案

我正在寻找一个对所有四个条件都适用的查询

3 个答案:

答案 0 :(得分:2)

对于每个问题列表,预期答案和提交的答案(您需要<?php $location = $_GET['a']; $locationSplit = explode(",", $location); $lat = $locationSplit[0]; $lng = $locationSplit[1]; $name = $locationSplit[2]; $fullLocation = $lat.",". $lng; // if latitude is between -90 / -180 <= lat / lng <= 90 / 180 // if (those checks are false) // die(0) ?> 来执行此操作,FULL OUTER JOIN加入是不够的)并计算匹配数。然后将此计数与预期答案的计数进行比较。

LEFT

您可以找到live demo here

答案 1 :(得分:0)

目前还不清楚你在这里要做什么,但下面的内容应该会帮助你开始:

select
    sa.user_id,
    sa.exam_id,
    qa.question_id,
    sa.submitted_option_id,
    qa.correct_option_id,
    case when sa.submitted_option_id = qa.correct_option_id then 1 else 0 end as question_score
from
    question_answer qa     
    LEFT JOIN user_exam_answer sa ON
        uea.question_id = qa.question_id
where
    sa.exam_id='html_001'
    and sa.user_id='user_123'

我希望qa表格也有exam_id列,但这不在您的图片中。

答案 2 :(得分:0)

请尝试以下方法......

Files already tracked by Git are not affected;

此查询使用SELECT user_id, exam_id, question_answer.question_id AS question_id, submited_option_id, correct_option_id, CASE WHEN correct_option_id = submited_option_id THEN 1 ELSE 0 END AS marked_option_id FROM question_answer LEFT JOIN user_exam_answer ON question_answer.question_id = user_exam_answer.question_id ORDER BY user_id, exam_id, question_id; 将两个表连接在一起,以便仍然返回未答复问题的记录。然后,它会将每个记录的正确答案与所提供的答案进行比较,如果匹配,则返回值LEFT JOIN,否则返回值1。然后,此比较的结果将作为字段0包含在输出中。然后对结果输出进行排序以方便阅读。

如果您有任何问题或意见,请随时发表评论。