Let's say I have the table
NAME | ID | REF
foo1 | 1 | NULL
foo2 | 2 | 1234
foo2 | 3 | 567
foo1 | 4 | NULL
foo3 | 5 | 89
I'd like to count all instances of NULL and NOT NULL in one query so that I can say
NAME | null | not null
foo1 | 0 | 2
foo2 | 2 | 0
foo3 | 0 | 1
I could run these two queries
select NAME,count(*) from TABLE where REF is not null
select NAME,count(*) from TABLE where REF is null
But I'm sure there must be a simple way to do it in one mysql query.
You can use SUM() on ISNULL() like this
select NAME, sum(isnull(REF)) as is_null, sum(not isnull(REF)) as is_not_null from TABLE group by NAME;
SUM(1) is equivalent to COUNT(*), so it will really make a count.
If it is ok with a solution that uses grouping you can try something like:
SELECT ISNULL(ref),COUNT(*) FROM TABLE GROUP BY ISNULL(ref)
At least it tells you how many row with a NULL in ref you have. This solution (good or not) could be extended with a select of GROUP_CONCAT on NAME if you need to select every individual name.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With