开发者

How to write condition wise result providing query?

开发者 https://www.devze.com 2023-03-18 12:03 出处:网络
I want to write a MySQL query that gives a condition wise result. For example. I have a table with question, answer value, user chose value fields.

I want to write a MySQL query that gives a condition wise result.

For example. I have a table with question, answer value, user chose value fields.

User can attend to answer that question many times.

qid     rightanz     wronganz
11         4             2
11         4             4
11         4             1
25         1             1

I want out put like this
qid     rightanz     wronganz
1开发者_运维问答1          1            2   
25          1            0   

I want to display how many times user provide right and wrong answers for that question? How can I write a MySQL query for that?


For all questions

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

For a specific question

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


SELECT SUM(IF(answer = 42, 1, 0)) AS correct_count, count(*) as total_count
FROM answers
WHERE user_id = 13

Supposing that user_id you want to inspect is 13 and correct answer is 42

0

精彩评论

暂无评论...
验证码 换一张
取 消