0

I have table user_answers :

id | quiz_id | user_id | question_id | choosen_answer_id |
1  |    1    |    2    |      1      |        5          |  
2  |    1    |    2    |      2      |        6          |  
3  |    1    |    2    |      3      |        7          |  
4  |    1    |    3    |      1      |        5          |  
5  |    1    |    3    |      2      |        8          |  
6  |    1    |    3    |      3      |        9          |  

I want to cont how many correct answers (same choosen_answer_id for same question_id ) has user with user_id = 3 compared with user_id = 2 on same quiz_id

In this example I should receive 1 because user with user_id = 3 answered correct only on question with question_id=1 (for user_id = 2, question_id = 1 choosen_answer_id = 5 and for user_id = 3, question_id = 1 choosen_answer_id = 5`).

Thanks

2
  • 3
    How to know whether the answer is correct or not? Commented Feb 16, 2019 at 21:35
  • "correct are answers" are from user_id = 2 but it does not matter. Мaybe "correct are answers" is not in place, and my question should be: count how many answers are same for same question Commented Feb 16, 2019 at 21:41

2 Answers 2

1

I understand that you are willing to count for how many questions both users have given the same answer. You could self-join the table as follows :

SELECT COUNT(*) AS number_of_identical_answers
FROM user_answers ua2
INNER JOIN user_answers ua3 
    ON  ua3.user_id           = 3 
    AND ua3.quiz_id           = ua2.quiz_id 
    AND ua3.question_id       = ua2.question_id 
    AND ua3.choosen_answer_id = ua2.choosen_answer_id
WHERE ua2.user_id = 2

If you want to display the joined records instead of counting them, you can change COUNT(*) to a list of columns from tables ua2 (answers of user 2) and ua3 (answers of user 3).

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

Comments

0
select user_id, count(*)
from table1 t1
join (select *from table1 where user_id = 2) t2
on t2.question_id = t1.question_id
where t2.choosen_answer_id  = t1.choosen_answer_id 
group by t1.user_id

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.