计算两列中具有等效值的行

时间:2015-02-19 22:10:24

标签: mysql sql

我希望找到输入答案与正确答案相同的行数。这是一个例子:

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

这里的正确查询是什么?

3 个答案:

答案 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

基本上,你需要做的是

  • 选择所有答案=正确的地方。
  • 按workerId对它们进行分组。
  • 计算每个组的行数(其中answer = correct)。

修改:要回答您编辑过的问题,

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  

DEMO