I’ve got three table where I’ve got field – area. So I decided to find sum of areas for every table and show it in one view.
I’ve created a query
select sum(x.area) as EquipmentSpace,sum(y.area) as ProductSpace,sum(z.area) as ShoppointSpace
from TEquipWarehouse as x,TProductWarehouse as y,TShopPoint as z
However when one of tables doesn’t have any record – the results of every field are NULL.
How to solve this problem?
There are several problems with your query. You are essentially doing a
CROSS JOIN. So, not only there will be zero rows in the intermediate result set when one table has zero rows but there will also be a lot of duplicate data when any of the tables has more than one rows. This will result in Null results in the first case and erroneous results in the second case.The only case that your query will work as expected is when all 3 tables have exactly one row.
To have what you want, you need 3 separate subqueries and then to combine them in one:
The
COALESCE()fubction is used to convert theNULLto 0, when a table has no rows.