我有一个存储过程如下:
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/0才能使用SSRS中的图表。
我尝试过使用coalesce并且无所作为。
SELECT COALESCE(SUM(c.Logged,0))
SELECT SUM(ISNULL(c.Logged,0))
有没有办法正确地格式化?
干杯,
背风处
把它放在外面:
SELECT COALESCE(
(
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
), 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.Location
WHERE s.Sites = @SiteName AND i.[month] = DATEADD(mm, DATEDIFF(mm, 0, GetDate()) -1,0)
GROUP BY s.Sites
顺便说一下,如果没有保证,不要在聚合函数中放置任何函数或表达式,例如不要把ISNULL,COALESCE放在SUM里面,使用function / expression里面的聚合跛子性能,查询将用表扫描执行
你必须像这样使用ISNULL
-
ISNULL(SUM(c.Logged), 0)
或者,正如迈克尔所说,你可以使用左外连接。
我在Oracle中遇到过这个问题。 Oracle没有ISNULL()
函数。但是,我们可以使用NVL()
函数来实现相同的结果:
NVL(SUM(c.Logged), 0)
我发现实现这一目标的最简单,最易读的方法是:
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
您可以将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
)
刚遇到这个问题,Kirtan的解决方案对我很有用,但语法有点偏差。我喜欢这样:
ISNULL(SUM(c.Logged), 0)
帖子帮助我解决了我的问题,所以感谢所有。