I have a database sample below:
Session Table:
SessionId (PK auto) SessionName
1 SODJW
Question Table:
QuestionId (PK auto) QuestionContent SessionId (FK) refer to Session
1 Blah 1
2 Blah Blah 1
3 Blah Blah Blah 1
Penalty_Marks Table:
PenaltyAnswerId PenaltyMarks QuestionId (FK) refer to Question
1 1 1
2 0 1
3 1 2
4 2 3
5 2 3
Now I want to Perform an SQL which counts the PenaltyMarks for a Session. So for that to happen, we need to know which QuestionId belongs to the SessionId and then count the marks.
My question is how can the SQL for this be written to be able to find the QuestionId‘s within the SessionId so then we can count the penalty marks? Reason I am asking this is because it is giving me incorrect count value.
My attempt:
SELECT COUNT(PenaltyMarks)
FROM Session s
INNER JOIN Question q ON s.SessionId = q.SessionId
INNER JOIN Penalty_Marks pm ON q.QuestionId = pm.QuestionId
WHERE s.SessionId = 1;
Your query returns number of rows, not the total Count of penalty marks. Also you said that you need to view each session’s question with the total penalty marks so you’ll have to group by session id and question id.
SQL Fiddle Demo