2016-05-17 42 views
3

我不知道我在做什麼來弄錯。我正在嘗試每月獲得usertb.id的數量。如果計數爲空,我希望顯示0。我正在使用包含月份和月份名稱的月份表的左外連接。請幫忙。我使用SQL SERVER 2008無法獲得每月計數的空值

SELECT 
    monthTB.name 
    ,subTB.name 
    ,COUNT(userTB.ID) 
FROM TDP_NetOps.dbo.sub_activity AS subTB 
    ,TDP_NetOps.dbo.month AS monthTB 
    LEFT OUTER JOIN TDP_NetOps.dbo.user_sub_activity AS userTB ON monthTB.ID = DATEPART(month, userTB.date_of_activity) 
WHERE 
    subTB.sub_activity_id = userTB.sub_activity_id 
    AND userTB.emp_id = 'xxxx' 
GROUP BY 
     monthTB.name 
     ,monthTB.ID 
     ,subTB.name 
ORDER BY 
     monthTB.ID ASC 
     ,subTB.name ASC 
+2

*從不*在'FROM'子句中使用逗號。 *始終*使用明確的'JOIN'語法。 –

回答

2

嗯,有幾件事情不對您的查詢:

首先,不使用隱JOIN語法(逗號分隔),使用加入的正確語法。其次,如果你確實使用它們,千萬不要將它們與明確的語法混合在一起,它總會導致錯誤。

最後,左連接的右表中的條件應該在ON子句內,在where中指定時,連接變爲內連接。 :

SELECT monthTB.name 
    , subTB.name 
    , COUNT(userTB.ID) 
FROM TDP_NetOps.dbo.sub_activity AS subTB 
CROSS JOIN TDP_NetOps.dbo.month AS monthTB 
LEFT OUTER JOIN TDP_NetOps.dbo.user_sub_activity AS userTB 
ON (monthTB.ID = DATEPART(month, userTB.date_of_activity) 
    AND subTB.sub_activity_id = userTB.sub_activity_id 
    AND userTB.emp_id = 'xxxx') 
GROUP BY monthTB.name 
     , monthTB.ID 
     , subTB.name 
ORDER BY monthTB.ID ASC 
     , subTB.name ASC 
+0

非常感謝sagi。我對sql很新,而且我仍然在努力學習。謝謝你的指點,我會看你說的。 – user2997109

0

WHERE子句撤消LEFT JOIN。我認爲這是你想要的邏輯:

SELECT monthTB.name, subTB.name 
     COUNT(userTB.ID) 
FROM (SELECT DISTINCT subTB.sub_activity_id 
     FROM TDP_NetOps.dbo.sub_activity subTB 
     WHERE subTB.emp_id = 'xxxx' 
    ) subTB CROSS JOIN 
    TDP_NetOps.dbo.month AS monthTB LEFT OUTER JOIN 
    TDP_NetOps.dbo.user_sub_activity userTB 
    ON monthTB.ID = DATEPART(month, userTB.date_of_activity) AND 
     subTB.sub_activity_id = userTB.sub_activity_id AND 
     subTB.emp_id = 'xxxx' 
GROUP BY monthTB.name, monthTB.ID, subTB.name 
ORDER BY monthTB.ID ASC, subTB.name ASC; 

我不知道,如果確實需要在emp_id第二濾波器。這取決於數據的樣子。

-1
SELECT monthTB.name 
    , subTB.name 
    , COALESCE(COUNT(userTB.ID),0) 
FROM TDP_NetOps.dbo.sub_activity AS subTB 
    , TDP_NetOps.dbo.month AS monthTB 
LEFT OUTER JOIN TDP_NetOps.dbo.user_sub_activity AS userTB ON monthTB.ID = DATEPART(month, userTB.date_of_activity) 
WHERE subTB.sub_activity_id = userTB.sub_activity_id 
    AND userTB.emp_id = 'xxxx' 
GROUP BY monthTB.name 
     , monthTB.ID 
     , subTB.name 
ORDER BY monthTB.ID ASC 
     , subTB.name ASC 
+0

仍然會這樣做! – sagi

+0

它不起作用。它不會顯示空值 – user2997109

+0

您是否可以提供臨時表中的示例數據?這很容易測試。 –