I have an exam database, with 4 tables: users, answers, questions and subjects.
user table
U_id | name
subjects table
S_id | Subject
questions table
Q_id | S_id | question | Correct
answers table
U_id | Q_id | answers
I need to find the number of correct answer per subject, per user.
My query
select U_id,questions.S_id ,count(Q_id)
from answers inner join questions on questions.q_id = answers.q_id
where questions.Correct = answers.answer
group by answers.U_id,questions.S_id
result:
1 | s1 | 2
1 | s2 | 3
1 | s3 | 1
2 | s1 | 1
2 | s2 | 1
That gives me the number of correct answer per subject, but if the user doesn't have a correct answer the S_id is not display, i need to display those with 0.
The result I need is
result:
1 | s1 | 2
1 | s2 | 3
1 | s3 | 1
2 | s1 | 1
2 | s2 | 1
2 | s3 | 0
Note: I´m using MySQL, but a MS SQL server answer is also fine.