我有一个案例,我需要选择在sql中回答该问题的每个问题用户数 我的表看起来像
table 1: questionnaire_question
id - question_text - thecorrectAnswer
table 2 :questionnaire_answers
id - user_id - question_id - user_answer - correct
正确列的值为0或1表示用户答案是否正确
答案 0 :(得分:0)
您可以加入表格并count
case
表达式来检查正确性:
SELECT q.id, cnt
FROM questionnaire_question q
JOIN (SELECT question_id, COUNT(CASE correct WHEN 1 THEN 1 END) AS cnt
FROM questionnaire_answers
GROUP BY question_id) a ON q.id = a.question_id
答案 1 :(得分:0)
使用LEFT JOIN
,GROUP BY
和COUNT
select
q.id,
count(distinct a.user_id) cnt -- can be replaced with count(*)
-- if a user has only at max one correct answer
-- for a given question
from questionnaire_question q
left join questionnaire_answers a
on q.id = a.question_id
where correct = 1
group by q.id;
答案 2 :(得分:0)
如果问题没有正确答案,则使用子查询,它将返回0
试试这个:
<div style="background-color:red;width:100vw;height:100vh">
</div>
<div>
hi
<ul>
<li>ho</li>
<li>ho</li>
<li>ho</li>
<li>ho</li>
<li>ho</li>
<li>ho</li>
</ul>
</div>
答案 3 :(得分:0)
select question_id, count(user_id)
from questionnaire_answers
where correct = 1
group by question_id
不需要加入,因为您已经通过包含正确的列来对模式进行非规范化。