Skip to content
Advertisement

How to return zero instead of null from a subquery when a condition is not met

I have the following data,

I want to sum up values of tags and deduct sum of D’s from sum of C’s. The below works fine if both tags are present for an id.

But if a tag is not available for an id either one of the subqueries will not return a value. In the above sample data there is only tag D for id 2 so the on C.Id = D.Id condition is failing. In this case i want zero to be returned.

Expected result

How can i do this? I am using mysql 8.0.17

Advertisement

Answer

Try the below – using conditional aggregation

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement