Wednesday, November 26, 2014

Lesson 45: Count row values with mysql

I just found out this interesting idea to sum count values in mysql.
suppose there's table like this:
PERSONVOTE
obamayes
mccainno
obamayes
obamano
mccainyes
obamayes
obamayes
obamano
mccainno
And now you want to count total of 'yes' and 'no' votes group by person, you can use this query:
SELECT person,
SUM(IF(vote = "yes", 1,0)) AS `yes_votes`,
SUM(IF(vote = "no", 1,0)) AS `no_votes`,
COUNT(vote) AS `total`
FROM votes
GROUP BY person
ORDER BY yes_votes DESC
note: you might need to modify the query to suit your specific requirement.


check out for article on:
http://www.randomsnippets.com/2008/10/05/how-to-count-values-with-mysql-queries/


No comments:

Post a Comment