COUNT will return number of non-null values, so you need a way to convert empty strings to nulls to get 0s.
SELECT location, COUNT(NULLIF(name,'')) AS count FROM table GROUP BY location;
Question
I have a simple MySQL DB with the following fields:
mysql> SELECT * from table;
+----+-----------+------+
| id | location | name |
+----+-----------+------+
| 1 | NJ | Gary |
| 2 | MN | Paul |
| 3 | AZ | |
| 4 | MI | Adam |
| 5 | NJ | |
| 6 | MN | Dave |
+----+-----------+------+
6 rows in set (0.00 sec)
I need to retrieve a list of how many people are from each state, excluding those who don't have a name. In other words, I'm trying to reproduce the following result:
+----------+-------+
| location | count |
+----------+-------+
| AZ | 0 |
| MI | 1 |
| MN | 2 |
| NJ | 1 |
+----------+-------+
I'm able to get close with
SELECT location, COUNT(*) AS count FROM table WHERE name!='' GROUP BY location;
However, COUNT(*) excludes the zero counts. I attempted to use JOIN along with the table produced by
SELECT DISTINCT location, null as count from table;
but a LEFT JOIN throws out the count column from the right table, and a RIGHT JOIN doesn't seem to include the zero rows or the actual counts for some reason.
I feel as though there's a MySQL command or something simple that I'm missing. I just need to find a way to merge the two tables based on location.
Can anybody point me in the right direction?
La solution
COUNT will return number of non-null values, so you need a way to convert empty strings to nulls to get 0s.
SELECT location, COUNT(NULLIF(name,'')) AS count FROM table GROUP BY location;