2012-02-26 104 views
0

我正在爲我的公司開發一個簡單的Intranet測驗引擎,我希望當用戶進入測驗的START頁面時查看他的部門的參與者總數。如果在測驗中的一個沒有參與者,下面的查詢應顯示爲零,但現在它不顯示零,我不知道爲什麼:爲什麼這個SQL查詢不顯示零COUNT函數?

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 

那麼如何解決這個問題?

回答

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; 
+0

它不顯示任何零。 – 2012-02-27 04:06:48

+0

此外,如果該部門的其中一名員工參與了其中一個可用測驗,則即使沒有參與者,該查詢也會在所有測驗中顯示參與人數爲1。 – 2012-02-27 04:36:51

+0

請顯示樣本數據和期望的結果,所以我們不必猜測。 – 2012-02-27 04:53:52