我希望找到输入答案与正确答案相同的行数。这是一个例子:
WorkerID Answer Correct
1 A A
1 B C
2 A D
然后我会得到以下结果:
WorkerID AnswerCount # Correct
1 2 1
2 1 0
到目前为止,我(概念上):
SELECT worker_id, count(*), count(Answer == Correct) FROM answer_table GROUP BY WorkerID
这里的正确查询是什么?
答案 0 :(得分:3)
您不希望count()
,想要sum()
:
SELECT worker_id, count(*) as AnswerCount, sum(Answer = Correct) as NumCorrect
FROM answer_table
GROUP BY WorkerID;
count()
计算表达式所采用的非NULL
值的数量。你想要计算匹配数,即真实数。
答案 1 :(得分:1)
我认为这就是你想要的:
select count(*)
from yourTable
where answer = correct
group by workerId
基本上,你需要做的是
修改:要回答您编辑过的问题,
select count(*), count(b.workerId)
from yourTable
left join (select *
from yourTable
where answer = correct) b using(workerId)
group by workerId
答案 2 :(得分:1)
使用它:
select workerid,count(*) as numberOfAnswers,
sum(case
when answer=correct then 1
else 0 end) as correctAnswers
from tbl
group by workerid