对查找表中的两列求和时出现 NULL 值

Tar*_*ooq 5 sql-server

我正在使用 SQL Server 并从两个查找表中获取数据,并希望获取这两列的总和。

当这两列(查找值)的总和给出NULL值时,就会出现问题。但是,我曾经COALESCE将这些值更改NULL为零。

我计算总和的行是这一行:(t2.[Score]+t3.[Score]) as Total

select  t1.[ID]
      ,t1.[District]
      ,[CLLG_Interventiond]
      ,t1.[UC_HH]
      ,t1.[Benef_Household]
      ,t1.[Duration_Years]
      ,t1.[Duration_Months]
      ,t1.[Budget_PKR]
      ,t1.[Priority]
      ,COALESCE(t2.[Score],0) as E_Score
      ,COALESCE(t3.[Score],0) as UCDP_Score
      ,(t2.[Score]+t3.[Score]) as Total
  FROM [dbo].[Data] as t1
  left outer join E_Growth as t2
  on t1.CLLG_Interventiond = t2.Intervention
  left outer join UCDP as t3
 on  t1.Priority = t3.Priority
Run Code Online (Sandbox Code Playgroud)

Sab*_*n B 13

尝试使用像这样的COALESCESUM

COALESCE(t2.[Score],0) + COALESCE(t3.[Score],0) as Total
Run Code Online (Sandbox Code Playgroud)

查询将如下所示:

select  t1.[ID]
      ,t1.[District]
      ,[CLLG_Interventiond]
      ,t1.[UC_HH]
      ,t1.[Benef_Household]
      ,t1.[Duration_Years]
      ,t1.[Duration_Months]
      ,t1.[Budget_PKR]
      ,t1.[Priority]
      ,COALESCE(t2.[Score],0) as E_Score
      ,COALESCE(t3.[Score],0) as UCDP_Score
      ,COALESCE(t2.[Score],0) + COALESCE(t3.[Score],0) as Total
  FROM [dbo].[Data] as t1
  left outer join E_Growth as t2
  on t1.CLLG_Interventiond = t2.Intervention
  left outer join UCDP as t3
 on  t1.Priority = t3.Priority
Run Code Online (Sandbox Code Playgroud)


Len*_*art 7

由于您已经处理了该问题,因此您可以嵌套查询并在外层计算总数:

SELECT T.*, T.E_SCORE + T.UCDP_SCORE AS total
FROM (
    select  t1.[ID]
           ,t1.[District]
           ,[CLLG_Interventiond]
           ,t1.[UC_HH]
           ,t1.[Benef_Household]
           ,t1.[Duration_Years]
           ,t1.[Duration_Months]
           ,t1.[Budget_PKR]
           ,t1.[Priority]
           ,COALESCE(t2.[Score],0) as E_Score
           ,COALESCE(t3.[Score],0) as UCDP_Score

   FROM [dbo].[Data] as t1
   left outer join E_Growth as t2
      on t1.CLLG_Interventiond = t2.Intervention
   left outer join UCDP as t3
      on  t1.Priority = t3.Priority
) as T
Run Code Online (Sandbox Code Playgroud)

CTE 可以以同样的方式使用