Quantcast
Channel: VBForums
Viewing all articles
Browse latest Browse all 15722

SQL - Query to return sum and 0 if no match is found

$
0
0
Hi
I have a table (HOC) containing the list of some items. I need to check another table (DA ) against HOC and sum up the occurrences of items and if no item is found then return 0 for sum.

My query:
Code:

Select HOC.ListItemName,
Sum(Case When DA.Hierarchy IS not null  then 1 else 0 End) As Total

--COALESCE(Sum(Case When DA.Hierarchy IS not null  then 1 else 0 End) , 0) As Total

From DV_ListItems as HOC
Left join DV_CaseOverview AS DA
On HOC.ListItemName = Cast(DA.HierarchyOrder as varchar(2)) + ': ' + DA.Hierarchy
Join [DV_Data_NEW] As NG 
ON NG.DEVIATION_NUMBER = DA.CaseID
Where
HOC.ListItemType = 'DV Hierarchy'
And ( Format(NG.[Completed_DATE],'yyyy-MM-dd')  >= '2020-06-25' And Format(NG.[Completed_DATE],'yyyy-MM-dd')  <= '2020-09-25') 
Group by HOC.ListItemName

This query does not show all the relevant items that exist in HOC; and give me the sum of only occurrences:

Name:  nullstuff.jpg
Views: 28
Size:  59.7 KB

How can I fix this? is this because of how I join them? Is it because of
Code:

On HOC.ListItemName = Cast(DA.HierarchyOrder as varchar(2)) + ': ' + DA.Hierarchy
and so if not both table contain the same item, then it won't show up in the result? but left join should be the correct method right?

Thanks in advance for your help.
Attached Images
 

Viewing all articles
Browse latest Browse all 15722

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>