0

我有一张看起来像这样的桌子

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

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

4

3 回答 3

2

尝试这个:

SELECT name, answer, COUNT(*) FROM yourtablenamehere GROUP BY name, answer
于 2012-12-04T01:06:50.337 回答
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
于 2012-12-04T03:26:34.543 回答
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
于 2012-12-10T16:17:50.940 回答