I am developing a simple Quiz Engine similar to that one in the ASP.NET website. I have the following database design:
-
User:
Username,Name,DivisionCode… etc -
Division:
SapCode,Division. -
Quiz:
QuizID,Title,IsSent,Description. -
UserQuiz:
UserQuizID,QuizID,DateTimeComplete,Score,Username
What I want now is to show an indicator in the Result page of each quiz that will show to the user the number of participants in the Employee’s Division who got 100 from the first time of taking the quiz. (so if the user takes the quiz again, his second try will not be considered in this query). So how to do that (How to show the number of participants who got 100 from the first time only)?
My Query which is not correct is:
SELECT dbo.Divisions.DivisionShortcut, COUNT(dbo.UserQuiz.Username) AS [Number of Participants]
FROM dbo.Divisions INNER JOIN
dbo.employee ON dbo.Divisions.SapCode = dbo.employee.DivisionCode INNER JOIN
dbo.UserQuiz ON dbo.employee.Username = dbo.UserQuiz.Username INNER JOIN
dbo.Quiz ON dbo.UserQuiz.QuizID = dbo.Quiz.QuizID
WHERE (dbo.UserQuiz.QuizID = @QuizID)
GROUP BY dbo.Divisions.DivisionShortcut, dbo.UserQuiz.Score
HAVING (dbo.UserQuiz.Score = 100)
And the desired output should be like this:

EDIT:
I am struggling now in being able to determine the QuizID:
;with OrderedAttempts as (
select Username,Score,QuizID,
ROW_NUMBER() OVER (PARTITION BY Username,QuizID ORDER BY DateTimeComplete) as rn
from UserQuiz
WHERE (dbo.UserQuiz.QuizID = @QuizID)
), FirstAttempts as (
select Username,Score,QuizID from OrderedAttempts where rn = 1
)
select
d.DivisionName,
COUNT(fa.Score)
from
Divisions d
left join
Employee e
left join
FirstAttempts fa
on
e.Username = fa.Username
on
d.SapCode = e.DivisionCode
group by
d.DivisionName
Simplest part of the query is find everyone who scored 100 on their first try:
Hopefully, from there, you can build up the rest of your query.