1

So I have a table that I populate with data from a quiz I have made. Why? So that I can spot questions that have a particular high/low success rate to determine if a questions need to be reworded. I think it will come in handy =) Any way, I'm having some troubles with "grouping" the answers to one row, and counting the occurrence of "correct" and "wrong".

The table looks like this:

+----+---------+----------+-------------+---------+------------+------------+
| id | user_id | stack_id | question_id | answer  | created_at | updated_at |
+----+---------+----------+-------------+---------+------------+------------+
|  1 |      34 |        1 |          45 | wrong   | NOW()      | NOW()      |
|  2 |      55 |        1 |          45 | correct | NOW()      | NOW()      |
|  3 |       2 |        3 |          13 | wrong   | NOW()      | NOW()      |
|  4 |      99 |        1 |          46 | correct | NOW()      | NOW()      |
|  5 |      12 |        3 |          13 | wrong   | NOW()      | NOW()      |
|  6 |      12 |        2 |          10 | correct | NOW()      | NOW()      |
+----+---------+----------+-------------+---------+------------+------------+

The column names correct, the data is mockup. But what I want is to group all question_ids, and count how many wrong and how many correct exists for that question_id.

(Im no sql guy, so please, if there is another way to display this data feel free!)

But the expected result should be something like:

+----------+-------------+-------+---------+
| stack_id | question_id | wrong | correct |
+----------+-------------+-------+---------+
|        1 |          45 |     1 |       1 |
|        3 |          13 |     1 |       0 |
|        1 |          46 |     0 |       1 |
|        2 |          10 |     0 |       1 |
+----------+-------------+-------+---------+

This is what I have so far, and it isn't much: SELECT answer, COUNT(*) FROM answers GROUP BY answer, and it seems to display the wrong information as well.

Adam
  • 1,231
  • 1
  • 13
  • 37

4 Answers4

1

Try this out:

    select stack_id,question_id,sum(case when answer='wrong' then 1 else 0 end) as wrong,
           sum(case when answer='correct' then 1 else 0 end) as correct
    from your_table
    group by stack_id,question_id;

Let me know if it works.

G.Arima
  • 1,171
  • 1
  • 6
  • 13
1

You can use the below SQL, to get the desired result:

select stack_id,question_id,
sum(case when answer='wrong' then 1 else 0 end) as wrong,
sum(case when answer='correct' then 1 else 0 end) as correct
from your_table_name
group by stack_id,question_id;
1

If this is MySQL, I would use this logic:

select stack_id, question_id,
       sum(answer = 'correct') as correct, sum(answer = 'wrong') as wrong
from t
group by stack_id, question_id;
Gordon Linoff
  • 1,242,037
  • 58
  • 646
  • 786
0
SELECT
    Answer
    , QuestionID
    , Count(Answer)
GROUP BY
   Answer, 
   QuesitonID
Doug Coats
  • 6,255
  • 9
  • 27
  • 49