所以我有一个表格,我填充了我所做的测验中的数据。为什么?因此,我可以发现具有特定高/低成功率的问题,以确定是否需要重写问题。我认为它会派上用场=)任何方式,我都会遇到一些问题"分组"一行的答案,并计算"正确"的出现次数。和"错误"。
表格如下:
+----+---------+----------+-------------+---------+------------+------------+
| 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() |
+----+---------+----------+-------------+---------+------------+------------+
列名正确,数据是模型。但我想要的是对所有question_id
进行分组,并计算wrong
存在多少correct
和question_id
个。{/ p>
(我没有sql的家伙,所以请,如果还有其他方式可以免费显示这些数据!)
但预期的结果应该是:
+----------+-------------+-------+---------+
| stack_id | question_id | wrong | correct |
+----------+-------------+-------+---------+
| 1 | 45 | 1 | 1 |
| 3 | 13 | 1 | 0 |
| 1 | 46 | 0 | 1 |
| 2 | 10 | 0 | 1 |
+----------+-------------+-------+---------+
这是我到目前为止所做的,并不是很多:SELECT answer, COUNT(*) FROM answers GROUP BY answer
,它似乎也显示错误的信息。
答案 0 :(得分:1)
试试这个:
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;
让我知道它是否有效。
答案 1 :(得分:1)
您可以使用以下SQL来获得所需的结果:
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;
答案 2 :(得分:1)
如果这是MySQL,我会使用这个逻辑:
select stack_id, question_id,
sum(answer = 'correct') as correct, sum(answer = 'wrong') as wrong
from t
group by stack_id, question_id;
答案 3 :(得分:0)
SELECT
Answer
, QuestionID
, Count(Answer)
GROUP BY
Answer,
QuesitonID