您好我想写一个mysql查询,它提供了条件明智的结果。
例如,。我有一个表格,包含问题,答案值,用户选择的值字段。
用户可以多次参加回答该问题。
qid rightanz wronganz 11 4 2 11 4 4 11 4 1 25 1 1 I want out put like this qid rightanz wronganz 11 1 2 25 1 0
我想显示用户为该问题提供正确和错误答案的次数? 我怎么能写一个mysql查询呢?任何人都可以帮助我吗?
答案 0 :(得分:2)
SELECT SUM(IF(answer = 42, 1, 0)) AS correct_count, count(*) as total_count
FROM answers
WHERE user_id = 13
假设您要检查的user_id
为13,正确答案为42
答案 1 :(得分:2)
对于所有问题
SELECT a.userId, q.qid
,SUM( CASE WHEN q.answer = a.answer THEN 1 ELSE 0 END) AS correct_answers
,SUM( CASE WHEN q.answer = a.answer THEN 0 ELSE 1 END) AS wrong_answers
FROM questions q
JOIN answers a ON q.qid = a.qid
GROUP BY a.userId, q.qid
针对具体问题
SELECT a.userId
,SUM( CASE WHEN q.answer = a.answer THEN 1 ELSE 0 END) AS correct_answers
,SUM( CASE WHEN q.answer = a.answer THEN 0 ELSE 1 END) AS wrong_answers
FROM questions q
JOIN answers a ON q.qid = a.qid
WHERE q.qid = <question_id>
GROUP BY a.userId