0

这是我的一个更大的查询。我想返回所有利润中心的列表,其中包含日期范围内的事件计数。我希望列出利润中心,即使在日期范围内没有报告任何事件。这一直运作良好。

然而,现在已经引入了一些利润中心为 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
4

2 回答 2

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. 它增加了不必要的处理,可能不需要。

于 2013-04-19T20:13:15.290 回答
0

由于您使用的是LEFT JOIN,因此空利润中心将在结果中显示为NULL。并且由于您正在使用DISTINCT它们,它们将被折叠成一行。对于Incident_Count 您可以使用的列coalesce(cast(h.Incident_Count as varchar(50)), 'N/A')

PS。我假设您使用的是 MS SQL Server 2012。

于 2013-04-19T19:59:03.420 回答