patternsqlModerate
NULL values appear when taking the sum of two columns taken from Lookup tables
Viewed 0 times
sumtablesthecolumnsnulltwotakenwhenvalueslookup
Problem
I am using SQL Server and taking data from two lookup tables and want to take the sum of these two columns.
The problem arises when the sum of these two columns (lookup values) gives
The line I am calculating the sum is this one:
The problem arises when the sum of these two columns (lookup values) gives
NULL values. However, I have used COALESCE to change the NULL values to zero.The line I am calculating the sum is this one:
(t2.[Score]+t3.[Score]) as Totalselect 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.PrioritySolution
Try to use
Like this:
The query will look like this:
COALESCE for the values in the SUMLike this:
COALESCE(t2.[Score],0) + COALESCE(t3.[Score],0) as TotalThe query will look like this:
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.PriorityCode Snippets
COALESCE(t2.[Score],0) + COALESCE(t3.[Score],0) as Totalselect 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.PriorityContext
StackExchange Database Administrators Q#315304, answer score: 13
Revisions (0)
No revisions yet.