Counting Different Values in a Column

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
marcdd2
Forum Newbie
Posts: 4
Joined: Tue Apr 06, 2010 7:58 pm

Counting Different Values in a Column

Post by marcdd2 »

I have a column, X, with three possible values 0, 1, 2. I can easily count the number of rows with 0 in them by using a basic WHERE statement in my SELECT, but then if I want to count the numbers of 1’s and then 2’s I have to do two more SELECTS. Is there a more efficient way to SELECT the whole table and then count the rows containing the specific values from that SELECT? Thanks.
User avatar
pickle
Briney Mod
Posts: 6445
Joined: Mon Jan 19, 2004 6:11 pm
Location: 53.01N x 112.48W
Contact:

Re: Counting Different Values in a Column

Post by pickle »

The COUNT() and GROUP BY might be helpful. Something like this perhaps?

Code: Select all

SELECT
  COUNT(`x`)
FROM
  `yourTable`
GROUP BY
  `x`
I don't think this'll work actually, but it's close.
Real programmers don't comment their code. If it was hard to write, it should be hard to understand.
User avatar
infolock
DevNet Resident
Posts: 1708
Joined: Wed Sep 25, 2002 7:47 pm

Re: Counting Different Values in a Column

Post by infolock »

you could use the mysql function count() and also group by


edit: heh, pickle, you're just too quick ;)
Post Reply