如何查看在测验中获得100分的参与者总数?

时间:2012-02-26 07:08:16

标签: sql sql-server-2008-r2

我正在开发一个类似于ASP.NET网站中的简单测验引擎。我有以下数据库设计:

  • 用户: UsernameNameDivisionCode ...等

  • 分部: SapCodeDivision

  • 测验: QuizIDTitleIsSentDescription

  • UserQuiz: UserQuizIDQuizIDDateTimeCompleteScoreUsername

我现在想要的是在每个测验的结果页面中显示一个指标,该指标将向用户显示员工部门的参与者数量从第一次参加测验后获得100 。 (因此,如果用户再次参加测验,则在此查询中不会考虑他的第二次尝试)。 那么如何做到(如何显示仅从第一次获得100的参与者人数)?

    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)

所需的输出应该是这样的: enter image description here

修改 我现在正在努力确定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

1 个答案:

答案 0 :(得分:2)

查询的最简单部分是找到第一次尝试得分100的所有人:

;with OrderedAttempts as (
     select UserName,Score,QuizID,
       ROW_NUMBER() OVER (PARTITION BY UserName,QuizID ORDER BY DateTimeCompleted) as rn
     from UserQuiz
), FirstAttempts as (
     select UserName,Score,QuizID from OrderedAttempts where rn = 1
)
select
    d.DivisionName,
    COUNT(fa.Score)
from
    Division d
        left join
    User u
        left join
    FirstAttempts fa
        on
            u.UserName = fa.UserName
        on
            d.SapCode = u.DivisionCode
group by
    d.DivisionName

希望从那里,您可以构建其余的查询。