Solved

MySQL syntax for count

Posted on 2011-09-28
3
249 Views
Last Modified: 2012-05-12
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

0
Comment
Question by:cpeters5
  • 2
3 Comments
 
LVL 41

Expert Comment

by:ralmada
ID: 36717101
select col1, sum(case when col2 > 0 then 1 else 0 end)
from tab group by col1
0
 

Author Comment

by:cpeters5
ID: 36717121
Perfect!
Thanks ralmada
0
 
LVL 41

Accepted Solution

by:
ralmada earned 500 total points
ID: 36717126
or

select col1, sum(if(col2 > 0,1,0))
from tab group by col1
0

Featured Post

Windows Server 2016: All you need to know

Learn about Hyper-V features that increase functionality and usability of Microsoft Windows Server 2016. Also, throughout this eBook, you’ll find some basic PowerShell examples that will help you leverage the scripts in your environments!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

All XML, All the Time; More Fun MySQL Tidbits – Dynamically Generate XML via Stored Procedure in MySQL Extensible Markup Language (XML) and database systems, a marriage we are seeing more and more of.  So the topics of parsing and manipulating XM…
Popularity Can Be Measured Sometimes we deal with questions of popularity, and we need a way to collect opinions from our clients.  This article shows a simple teaching example of how we might elect a favorite color by letting our clients vote for …
Are you ready to implement Active Directory best practices without reading 300+ pages? You're in luck. In this webinar hosted by Skyport Systems, you gain insight into Microsoft's latest comprehensive guide, with tips on the best and easiest way…

740 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question