更改SUM返回NULL为零

时间:2010-05-10 12:55:29

标签: sql null sum zero coalesce

我的存储过程如下:

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 containts a generated list of total incidents by site/date (monthly)
'If a site doesnt have any incidents that month it wont be listed.

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

我尝试过使用coalesce并且无所作为。

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

有没有办法正确格式化?

干杯,

6 个答案:

答案 0 :(得分:46)

把它放在外面:

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里面,使用函数/表达式聚合跛行性能,查询将用表扫描执行

答案 1 :(得分:23)

你必须像这样使用ISNULL -

ISNULL(SUM(c.Logged), 0)      

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

答案 2 :(得分:7)

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

NVL(SUM(c.Logged), 0)

答案 3 :(得分:2)

我发现实现这一目标的最简单,最可读的方法是:

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  

答案 4 :(得分: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
)

答案 5 :(得分:1)

刚遇到这个问题,Kirtan的解决方案对我很有帮助,但语法有点偏。我确实喜欢这个:

ISNULL(SUM(c.Logged), 0)

Post帮助我解决了我的问题,但感谢所有人。