这是我有一个更大的查询。我想返回所有利润中心的列表,事件计数在日期范围内。我希望列出利润中心,即使日期范围内没有报告任何事件。这一直很好。
然而,现在已经引入了一些利润中心为NULL的记录。我希望那些在列表中显示为'N / A'的事件计数为NULL。
SELECT DISTINCT cast(plants.profit_ctr as varchar(50)) + ' - ' + cast(plants.profit_ctr_name as varchar(50)) AS Profit_Center, COALESCE(h.Incident_Count, 0) AS Incident_Count
FROM JMART.[safety].vwHELPForms AS plants
LEFT OUTER JOIN
(SELECT profit_ctr, COUNT(*) AS Incident_Count
FROM JMART.[safety].vwHELPForms
WHERE cast(rec_date as date) >= cast(@startdate as date)
AND cast(rec_date as date) <= cast(@enddate as date) AND ratings > 0
GROUP BY profit_ctr) AS h
ON h.profit_ctr = plants.profit_ctr
我该如何做到这一点?
修改的
如果我跑
SELECT profit_ctr, COUNT(*) AS Incident_Count
FROM JMART.[safety].vwHELPForms
WHERE cast(rec_date as date) >= cast(@startdate as date)
AND cast(rec_date as date) <= cast(@enddate as date) AND ratings > 0
GROUP BY profit_ctr
我得到了
NULL 295
101100 7483
101150 116
101200 445
101400 3784
我试过
SELECT DISTINCT cast(plants.profit_ctr as varchar(50)) + ' - ' + cast(plants.profit_ctr_name as varchar(50)) AS Profit_Center,
COALESCE((SELECT COUNT(*) AS Incident_Count FROM JMART.[safety].vwHELPForms AS h
WHERE profit_ctr = plants.profit_ctr AND cast(rec_date as date) >= cast(@startdate as date)
AND cast(rec_date as date) <= cast(@enddate as date) AND ratings > 0
GROUP BY profit_ctr), 0) AS Incident_Count
FROM JMART.[safety].vwHELPForms AS plants
order by Profit_Center
给了我(与我目前得到的相同)
NULL 0
101100 7483
101150 116
101200 445
101400 3784
我想要
N/A 295
101100 7483
101150 116
101200 445
101400 3784
答案 0 :(得分:1)
NULL值将进入连接中的第二个表,而不是第一个表。所以,它们被left outer join
迷失了。相反,您想使用full outer join
:
SELECT DISTINCT
coalesce(cast(plants.profit_ctr as varchar(50)) + ' - ' + cast(plants.profit_ctr_name as varchar(50)), 'N/A') AS Profit_Center,
COALESCE(h.Incident_Count, 0) AS Incident_Count
FROM JMART.[safety].vwHELPForms plants full OUTER JOIN
(SELECT profit_ctr, COUNT(*) as Incident_Count
FROM JMART.[safety].vwHELPForms
WHERE cast(rec_date as date) >= cast(@startdate as date) AND
cast(rec_date as date) <= cast(@enddate as date) AND ratings > 0
GROUP BY profit_ctr
) h
ON h.profit_ctr = plants.profit_ctr
假设profit_ctr
表中没有重复plants
,您可以省略distinct
。它增加了不必要的处理,可能不需要。
答案 1 :(得分:0)
由于您使用的是LEFT JOIN
,因此空利润中心会在结果中显示为NULL
。由于您使用DISTINCT
,因此它们将折叠为一行。对于Incident_Count
列,您可以使用coalesce(cast(h.Incident_Count as varchar(50)), 'N/A')
PS。我假设您正在使用MS SQL Server 2012。