1

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.

3
  • something about the inner join... outer join, cross join... too long ago... Try it. Commented Feb 6, 2011 at 4:32
  • the given table structure doesn't map to your query Commented Feb 6, 2011 at 4:37
  • I added S_id to the questions table Commented Feb 6, 2011 at 4:56

1 Answer 1

2
select u.U_id, q.S_id, count(a.q_id) 
from users u
cross join questions q
left join answers a on q.q_id = a.q_id and u.u_id = a.u_id and q.Correct = a.answer
group by u.U_id, q.S_id
Sign up to request clarification or add additional context in comments.

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.