Changing a SUM returned NULL to zero

前端 未结 6 1728
旧巷少年郎
旧巷少年郎 2021-02-05 01:54

I have a stored procedure as follows:

CREATE PROC [dbo].[Incidents]
(@SiteName varchar(200))
AS
SELECT
(  
    SELECT SUM(i.Logged)  
    FROM tbl_Sites s  
             


        
相关标签:
6条回答
  • 2021-02-05 02:25

    The easiest, and most readable, way I've found to accomplish this is through:

    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  
    
    0 讨论(0)
  • 2021-02-05 02:29

    Put it outside:

    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
    

    If you are returning multiple rows, change INNER JOIN to 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  
    

    By the way, don't put any function or expression inside aggregate functions if it's not warranted, e.g. don't put ISNULL, COALESCE inside of SUM, using function/expression inside aggregation cripples performance, the query will be executed with table scan

    0 讨论(0)
  • 2021-02-05 02:33

    You could wrap the SELECT in another SELECT like so:

     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
    )
    
    0 讨论(0)
  • 2021-02-05 02:37

    Just ran into this problem, Kirtan's solution worked for me well, but the syntax was a little off. I did like this:

    ISNULL(SUM(c.Logged), 0)
    

    Post helped me solve my problem though so thanks to all.

    0 讨论(0)
  • 2021-02-05 02:39

    You'll have to use ISNULL like this -

    ISNULL(SUM(c.Logged), 0)      
    

    Or, as Michael said, you can use a Left Outer Join.

    0 讨论(0)
  • 2021-02-05 02:41

    I encountered this problem in Oracle. Oracle does not have an ISNULL() function. However, we can use the NVL() function to achieve the same result:

    NVL(SUM(c.Logged), 0)
    
    0 讨论(0)
提交回复
热议问题