Skip to content
Advertisement

How to write condition wise result providing query?

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
11          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?

Advertisement

Answer

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
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement