如果有空,ISNULL不显示列?

时间:2013-03-13 02:56:47

标签: sql select sql-server-2008-r2 isnull

我有查询

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

它的工作但它必须显示Category表中的所有类别,即使它们是null 但是当我运行我的查询时,它看起来像这样

来自类别表的

类别

Child
Infant
Newborn
Pregnant
Postpartum
Senior

任何创意方式ISNULL都必须按原样运作?

1 个答案:

答案 0 :(得分:2)

因为您已过滤WHERE子句中的行,导致其行为类似于INNER JOIN。您需要将条件放在ON子句中,因为我猜测在表agencyid 上找到了列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