2013-03-13 36 views
1

我有查詢方式ISNULL不顯示colums如果有空?

SELECT [Category] = ISNULL (c.Category,'0'), 
     COUNT (cl.ClientID) as [3 Mo Clients] 
FROM Category c LEFT JOIN clients cl ON cl.CategCode = c.CategCode 
WHERE agencyid =2 
GROUP BY c.Category, c.CategCode 

它的工作,但它必須表現出從分類表中的所有類別,即使他們與空 但是當我運行我的查詢它看起來像從分類表這

類別

Child 
Infant 
Newborn 
Pregnant 
Postpartum 
Senior 

任何想法waylike ISNULL doent工作,因爲它必須是?

+0

不工作:) – Andrey 2013-03-13 03:04:18

回答

2

,因爲您已經過濾了WHERE子句中的行,導致它像INNER JOIN一樣行事。您需要將條件放在ON條款中,因爲我猜測列在表CategCode上找到。

SELECT [Category] = ISNULL (c.Category,'0'), 
     COUNT (cl.ClientID) as [3 Mo Clients] 
FROM Category c 
     LEFT JOIN clients cl 
      ON cl.CategCode = c.CategCode AND 
       cl.agencyid = 2 
GROUP BY c.Category, c.CategCode 

更新1

SELECT [Category] = ISNULL (c.Category,'0'), 
     COUNT (cl.ClientID) as [3 Mo Clients], 
     SUM(CASE WHEN statusid in (1,2) THEN 1 ELSE 0 END) [Status_1_2] 
FROM Category c 
     LEFT JOIN clients cl 
      ON cl.CategCode = c.CategCode AND 
       cl.agencyid = 2 
GROUP BY c.Category, c.CategCode 
+0

你知道如何添加一個多列,將來自客戶端的表'statusid在(1,2)計數的ClientID'並以同樣的方式顯示?因爲現在我不能添加where子句。 – Andrey 2013-03-13 03:10:15

+0

您是否嘗試過使用** IN **,'cl.agencyid IN(1,2)'而不是'cl.agencyid = 2'? – 2013-03-13 03:12:01

+0

但我需要一個額外的列。我嘗試了SELECT [Category] ​​= ISNULL(c.Category,'0'), COUNT(cl.ClientID)as [3 Mo Clients] ,(select COUNT(cl.ClientID)from clients cl where agencyID = 2 and (1,2)group by cl.CategCode中的statusid)爲'1' FROM Category c LEFT JOIN clients cl ON cl.CategCode = c.CategCode AND cl.agencyid = 2 GROUP BY c.Category,c.CategCode '但是在第三欄中它只顯示所有在(1,2) – Andrey 2013-03-13 03:14:23