SQL: sum 3 columns when one column has a null value?

前端 未结 9 2064
北恋
北恋 2020-12-05 09:37
SELECT 
    sum(TotalHoursM)
          + (TotalHoursT)
          + (TotalHoursW)
          + (TotalHoursTH)
          + (TotalHoursF) 
          AS TOTAL
FROM LeaveR         


        
9条回答
  •  既然无缘
    2020-12-05 09:44

    The previous answers using the ISNULL function are correct only for MS Sql Server. The COALESCE function will also work in SQL Server. But will also work in standard SQL database systems. In the given example:

    SELECT sum(COALESCE(TotalHoursM,0))
              + COALESCE(TotalHoursT,0)
              + COALESCE(TotalHoursW,0)
              + COALESCE(TotalHoursTH,0)
              + COALESCE(TotalHoursF,0) AS TOTAL FROM LeaveRequest
    

    This is identical to the ISNULL solution with the only difference being the name of the function. Both work in SQL Server but, COALESCE is ANSI standard and ISNULL is not. Also, COALESCE is more flexible. ISNULL will only work with two parameters. If the first parameter is NULL then the value of the second parameter is returned, else the value of the first is returned. COALESCE will take 2 to 'n' (I don't know the limit of 'n') parameters and return the value of the first parameter that is not NULL. When there are only two parameters the effect is the same as ISNULL.

提交回复
热议问题