这是我的一个更大的查询。我想返回所有利润中心的列表,其中包含日期范围内的事件计数。我希望列出利润中心,即使在日期范围内没有报告任何事件。这一直运作良好。
然而,现在已经引入了一些利润中心为 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