我正在为我的公司开发一个简单的Intranet测验引擎,我希望当用户进入测验的START页面时,可以看到他所在部门的参与者总数。如果其中一个测验中没有参与者,则以下查询应显示为零,但现在它不显示零,我不知道原因:
SELECT dbo.Divisions.DivisionShortcut AS Division, COUNT(DISTINCT 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.Quiz.QuizID = @QuizID) AND (dbo.Employee.Username = @Username)
GROUP BY dbo.Divisions.DivisionShortcut
那么如何解决?
答案 0 :(得分:1)
您需要一个外部联接来说明您所在部门的任何人尚未参加测验的情况。
SELECT
Division = d.DivisionShortcut,
[Number of Participants] = COUNT(DISTINCT uq.Username)
FROM dbo.Divisions AS d
INNER JOIN dbo.Employee AS e
ON d.SapCode = e.DivisionCode
LEFT OUTER JOIN dbo.UserQuiz AS uq
ON e.Username = uq.Username
LEFT OUTER JOIN dbo.Quiz AS q
ON uq.QuizID = q.QuizID
AND dbo.Quiz.QuizID = @QuizID
WHERE e.Username = @Username
GROUP BY d.DivisionShortcut;