I have over 10 tables that I want the count of some values for each date in the tables but for the purpose of this request, I will limit to only 2 tables and 2 dates.
I want to replace whenever a query does not return a result with zero instead. I searched and only one that is awfully similar to what I want is found here: Replace No Result With Zero but the answer provided does not suit my purpose and the original question, to the best of my knowledge, was not presented properly. It gave me the inspiration to tailor my query in similar format though. This is the query:
SELECT a.*
FROM
(SELECT
'count_male_account' AS count_name,
date,
count(*) AS actual_count
FROM gender_table
WHERE date IN ('2021-10-09', '2021-10-10') -- selected only 2 from over 4 months worth
AND gender = 'male'
GROUP BY date
UNION
SELECT
'count_female_account' AS count_name,
date,
count(*) AS actual_count
FROM gender_table
WHERE date IN ('2021-10-09', '2021-10-10') -- selected only 2 from over 4 months worth
AND gender = 'female'
GROUP BY date
UNION
SELECT
'count_null_address' AS count_name,
date,
count(*) AS actual_count
FROM address_table
WHERE date IN ('2021-10-09', '2021-10-10') -- selected only 2 from over 4 months worth
AND address is NULL
GROUP BY date
UNION
SELECT
'count_public_phone_number' AS count_name,
date,
count(*) AS actual_count
FROM address_table
WHERE date IN ('2021-10-09', '2021-10-10') -- selected only 2 from over 4 months worth
AND phone_cat = 'public'
GROUP BY date) a
ORDER BY date desc, count_name;
My output from the query is
+-------------------------+----------+------------+
|count_name |date |actual_count|
+-------------------------+----------+------------+
|count_female_account |2021-10-10|3217 |
|count_male_account |2021-10-10|306 |
|count_public_phone_number|2021-10-10|372 |
|count_female_account |2021-10-09|3787 |
|count_male_account |2021-10-09|377 |
|count_null_address |2021-10-09|5 |
+-------------------------+----------+------------+
But in my desired output, I want all rows to be there even if there are no count.
For example, for date = 2021-10-10, there's no address with null value in the address column, hence instead of the count_null_address to be missing in my result, I want it's actual_count = 0. Same goes for date = 2021-10-09 where there are no public phone number.
+-------------------------+----------+------------+
|count_name |date |actual_count|
+-------------------------+----------+------------+
|count_female_account |2021-10-10|3217 |
|count_male_account |2021-10-10|306 |
|count_null_address |2021-10-10|0 |
|count_public_phone_number|2021-10-10|372 |
|count_female_account |2021-10-09|3787 |
|count_male_account |2021-10-09|377 |
|count_null_address |2021-10-09|5 |
|count_public_phone_number|2021-10-09|0 |
+-------------------------+----------+------------+