36

我有一个存储过程如下:

CREATE PROC [dbo].[Incidents]
(@SiteName varchar(200))
AS
SELECT
(  
    SELECT SUM(i.Logged)  
    FROM tbl_Sites s  
    INNER JOIN tbl_Incidents i  
    ON s.Location = i.Location  
    WHERE s.Sites = @SiteName AND i.[month] = DATEADD(mm, DATEDIFF(mm, 0, GetDate()) -1,0)  
    GROUP BY s.Sites  
)  AS LoggedIncidents

'tbl_Sites contains a list of reported on sites.
'tbl_Incidents contains a generated list of total incidents by site/date (monthly)
'If a site doesn't have any incidents that month it wont be listed.

我遇到的问题是该站点本月没有任何事件,因此当我运行此 proc 时,我为该站点返回了一个 NULL 值,但我需要返回一个零/0 才能在其中使用SSRS 中的图表。

我试过使用 coalesce 和 isnull 无济于事。

    SELECT COALESCE(SUM(c.Logged,0))
    SELECT SUM(ISNULL(c.Logged,0))

有没有办法让这个格式正确?

干杯,

4

6 回答 6

59

放在外面:

SELECT COALESCE(

(  
    SELECT SUM(i.Logged)  
    FROM tbl_Sites s  
    INNER JOIN tbl_Incidents i  
    ON s.Location = i.Location  
    WHERE s.Sites = @SiteName AND i.[month] = DATEADD(mm, DATEDIFF(mm, 0, GetDate()) -1,0)  
    GROUP BY s.Sites  
), 0)  AS LoggedIncidents

如果要返回多行,请将 INNER JOIN 更改为LEFT JOIN

SELECT COALESCE(SUM(i.Logged),0)
FROM tbl_Sites s  
LEFT JOIN tbl_Incidents i  
ON s.Location = i.Location  
WHERE s.Sites = @SiteName AND i.[month] = DATEADD(mm, DATEDIFF(mm, 0, GetDate()) -1,0)  
GROUP BY s.Sites  

顺便说一句,如果没有必要,不要将任何函数或表达式放在聚合函数中,例如不要将 ISNULL、COALESCE 放在 SUM 中,在聚合中使用函数/表达式会削弱性能,查询将使用表扫描执行

于 2010-05-10T12:57:42.250 回答
33

你必须ISNULL像这样使用 -

ISNULL(SUM(c.Logged), 0)      

或者,正如迈克尔所说,您可以使用左外连接。

于 2010-05-10T12:58:33.673 回答
9

我在Oracle中遇到了这个问题。Oracle 没有ISNULL()函数。但是,我们可以使用该NVL()函数来实现相同的结果:

NVL(SUM(c.Logged), 0)
于 2016-10-01T00:50:24.930 回答
3

我发现完成此任务的最简单、最易读的方法是:

CREATE PROC [dbo].[Incidents]
(@SiteName varchar(200))

AS

    SELECT SUM(COALESCE(i.Logged, 0)) AS LoggedIncidents
    FROM tbl_Sites s  
    INNER JOIN tbl_Incidents i  
    ON s.Location = i.Location  
    WHERE s.Sites = @SiteName 
          AND i.[month] = DATEADD(mm, DATEDIFF(mm, 0, GetDate()) -1,0)  
    GROUP BY s.Sites  
于 2010-05-10T13:10:53.390 回答
1

您可以将 SELECT 包装在另一个 SELECT 中,如下所示:

 CREATE PROC [dbo].[Incidents]
(@SiteName varchar(200))

AS

SELECT COALESCE(TotalIncidents  ,0)
FROM (
  SELECT
  (  
    SELECT SUM(i.Logged) as TotalIncidents  
    FROM tbl_Sites s  
    INNER JOIN tbl_Incidents i  
    ON s.Location = i.Location  
    WHERE s.Sites = @SiteName AND i.[month] = DATEADD(mm, DATEDIFF(mm, 0, GetDate()) -1,0)  
    GROUP BY s.Sites  
  )  AS LoggedIncidents
)
于 2010-05-10T12:59:49.520 回答
1

刚遇到这个问题,Kirtan 的解决方案对我来说效果很好,但是语法有点不对劲。我确实喜欢这样:

ISNULL(SUM(c.Logged), 0)

邮政帮助我解决了我的问题,所以感谢所有人。

于 2010-08-12T20:04:55.507 回答