Link to home
Start Free TrialLog in
Avatar of cpeters5
cpeters5

asked on

MySQL syntax for count

I want to count records in a table that satisfying a condition.  But I also want to output a zero if there is no such record.  For example

Tab=
id   col1    col2    
1    a        5
2    b        0
3    c        2        
4    a       12

The query
select col1, count(*) from tab where col2 > 0 group by 1;
would return
a  2
c  1

I want the put put to also show
b   0

How do I do this?
pax

Avatar of ralmada
ralmada
Flag of Canada image

select col1, sum(case when col2 > 0 then 1 else 0 end)
from tab group by col1
Avatar of cpeters5
cpeters5

ASKER

Perfect!
Thanks ralmada
ASKER CERTIFIED SOLUTION
Avatar of ralmada
ralmada
Flag of Canada image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial