如何根据测验的标题显示此查询的结果?

时间:2012-07-02 04:54:02

标签: sql sql-server-2008-r2

我有以下数据库设计:

Employee Table: Username, Name.....
Divisions Table: SapCode, DivisionShortcut, DivisionName 
Quiz Table: QuizID, Title, IsSent, Description
UserQuiz Table: UserQuizID, QuizID, DateTimeComplete, Score, Username 

(IsSent是一个标志,指的是已发送给所有员工的测验)

我有以下查询,它会检索已发送的测验的标题以及每个部门的参与者总数。该查询运行良好,但它有一个小错误。检索到的结果将从上次发送的测验开始显示。测验的标题就像测验12,测验11和测验10.现在,查询显示(测验9)是最后一个测验。但是,最后一个测验已发送(测验12)。

那么如何修改此查询以获得正确的结果?

查询:

SELECT     TOP (100) PERCENT COUNT(DISTINCT dbo.UserQuiz.Username) AS [Total Number of Participants], dbo.Divisions.DivisionShortcut, dbo.Quiz.Title
FROM         dbo.employee INNER JOIN
                      dbo.UserQuiz ON dbo.employee.Username = dbo.UserQuiz.Username INNER JOIN
                      dbo.Quiz ON dbo.UserQuiz.QuizID = dbo.Quiz.QuizID INNER JOIN
                      dbo.Divisions ON dbo.employee.DivisionCode = dbo.Divisions.SapCode
WHERE     (dbo.Quiz.IsSent = 1)
GROUP BY dbo.Divisions.DivisionShortcut, dbo.Quiz.Title
ORDER BY dbo.Quiz.Title DESC

2 个答案:

答案 0 :(得分:1)

您按标题排序,标题是varchar。 “测验11”出现在“测验9”之前,按字母顺序排序,因为“1”和“11”出现在“9”之前。

现在,我不确定你如何填充你的QuizID值,但如果它是一个自动填充的整数,那么最好使用

ORDER BY dbo.Quiz.QuizID DESC

代替。

更好的是,在Quiz表中添加CreatedDate,然后按该列排序。

答案 1 :(得分:0)

最后,经过数百万次尝试,我得到了答案。解决方案非常简单:

SELECT     TOP (100) PERCENT COUNT(DISTINCT dbo.UserQuiz.Username) AS [Total Number of Participants], dbo.Divisions.DivisionShortcut, dbo.Quiz.Title
FROM         dbo.employee INNER JOIN
                      dbo.UserQuiz ON dbo.employee.Username = dbo.UserQuiz.Username INNER JOIN
                      dbo.Quiz ON dbo.UserQuiz.QuizID = dbo.Quiz.QuizID INNER JOIN
                      dbo.Divisions ON dbo.employee.DivisionCode = dbo.Divisions.SapCode
WHERE     (dbo.Quiz.IsSent = 1)
GROUP BY dbo.Divisions.DivisionShortcut, dbo.Quiz.Title, dbo.UserQuiz.QuizID
ORDER BY dbo.UserQuiz.QuizID DESC