-1

我有以下数据库设计:

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

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

我有以下查询,可检索已发送的测验的标题以及每个部门的参与者总数。该查询运行良好,但其中有一个小错误。检索到的结果将从上次发送的测验开始显示。测验的标题类似于 Quiz 12、Quiz 11 和 Quiz 10。现在,查询显示 (Quiz 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
4

2 回答 2

1

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

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

ORDER BY dbo.Quiz.QuizID DESC

反而。

更好的是,在 Quiz 表中添加 CreatedDate 并改为按该列排序。

于 2012-07-02T05:03:08.240 回答
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
于 2012-07-02T05:04:05.307 回答