1

我有疑问

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

任何想法方式ISNULL都不能正常工作?

4

1 回答 1

2

因为您已经过滤了子句中的行,WHERE导致它的行为类似于INNER JOIN. 您需要将条件放在ON子句中,因为我猜想agencyid在 table 上找到了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
于 2013-03-13T02:59:01.333 回答