3

I am looking to find the count of rows where the entered answer is the same as the correct answer. Here's an example:

WorkerID      Answer      Correct
1             A           A
1             B           C
2             A           D

I would then get the following result:

WorkerID    AnswerCount # Correct
1           2           1
2           1           0

So far I have (conceptually):

SELECT worker_id, count(*), count(Answer == Correct) FROM answer_table GROUP BY WorkerID

What would be the correct query here?

1
  • You can combine conditions in your WHERE, such as WHERE (Answer = Correct) AND (your other criteria....). Commented Feb 19, 2015 at 22:16

3 Answers 3

3

You don't want count(), you want sum():

SELECT worker_id, count(*) as AnswerCount, sum(Answer = Correct) as NumCorrect
FROM answer_table
GROUP BY WorkerID;

count() counts the number of non-NULL values that the expression takes on. You want to count the number of matches, which is the number of trues.

Sign up to request clarification or add additional context in comments.

Comments

1

I think this is what you want :

select count(*)
from yourTable
where answer = correct
group by workerId

Basically, what you need to do is

  • Select all where answer = correct.
  • group them by workerId.
  • count the num of rows (where answer = correct) for each group.

Edit : To answer to your edited question,

select count(*), count(b.workerId)
from yourTable
left join (select * 
           from yourTable 
           where answer = correct) b using(workerId)
group by workerId

1 Comment

Please see updated question, as I cannot use a WHERE clause in the statement, it needs to be part of the select.
1

use this:

select workerid,count(*) as numberOfAnswers,
sum(case
           when answer=correct then 1
           else 0 end) as correctAnswers
from tbl
group by workerid  

DEMO

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.