SQL按组计数

时间:2012-12-04 00:57:12

标签: mysql select join nested

我有一张看起来像这样的表

id  name answer   question
1   john  correct 1
1   john  correct 2
1   john  correct 3
1   john  wrong   4
2   lee   wrong   1
2   lee   correct 2
2   lee   correct 3
3   ana   correct 1
3   ana   wrong   2

我希望能够获得所有唯一身份用户的列表,并查看他们有多少问题是正确的,有多少是错误的。

我试过这样的事情,但似乎无法让它发挥作用:

SELECT id, user_id, name, question_id, (select count(answer) from table where answer = 'CORRECT') as correct, (select count(answer) from table where answer= 'WRONG') as wrong FROM table GROUP BY user_id

有人可以帮助我让我走上正轨吗?感谢

3 个答案:

答案 0 :(得分:2)

试试这个:

SELECT name, answer, COUNT(*) FROM yourtablenamehere GROUP BY name, answer

答案 1 :(得分:1)

你用条件总和做你想做的事:

select name, sum(case when answer = 'correct' then 1 else 0 end) as correct,
       sum(case when answer = 'wrong' then 1 else 0 end) as wrong
from table t
group by name

答案 2 :(得分:0)

对于MySQL,它可能是这样的:

SELECT user_id, name,SUM(IF(answer='correct',1,0)) AS correct,SUM(IF(answer='wrong',1,0)) as wrong FROM table GROUP BY user_id