I have query

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

its work BUT it must show all category from Category table even if they are with null but when i run my query it looks like this

category from Category table

Child
Infant
Newborn
Pregnant
Postpartum
Senior

Any Ideas way ISNULL doent work as it must be?

有帮助吗?

解决方案

because you have filter the rows in the WHERE clause causing it to act like INNER JOIN. You need to put the condition in the ON clause because I'm guessing that column agencyid is found on 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

UPDATE 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
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top