我有查询
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
都必须按原样运作?
答案 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