Default values ββfor COUNT in MySQL
I have a table that looks something like this:
+-------+-----+
|country|prop1|
+-------+-----+
|RO | 1 |
|RO | 2 |
|UK | 1 |
|IT | 2 |
+-------+-----+
I want to count rows for which prop1 is not null and I am using the following select:
SELECT `country`, COUNT(*) as number FROM table GROUP BY `country`;
this will return:
+-------+------+
|country|number|
+-------+------+
|RO | 2 |
|UK | 1 |
|IT | 1 |
+-------+------+
however I need the following:
+-------+------+
|country|number|
+-------+------+
|RO | 2 |
|UK | 1 |
|IT | 1 |
|FR | 0 |
+-------+------+
Do you think you can write something like this directly in SQL? I was thinking something like specifying a list of possible values ββfor "country" and a default value (0) if not found in the table.
source to share
It's not obvious in your example where it comes from FR
.
MySQL
does not have a list of countries within it, so the country codes must be taken from somewhere.
If you have all countries inside mytable
(with prop
possibly set to NULL
):
SELECT country, COUNT(prop) as number
FROM mytable
GROUP BY
country
If you have countries in a separate table (and the country may not be in mytable
):
SELECT c.id, COUNT(m.prop) as number
FROM countries c
LEFT JOIN
mytable m
ON m.country = c.id
GROUP BY
c.id
source to share