MySQL – Counting how many rows have a particular value

Working on a SugarCRM dashboard today, and I needed to count how many records had one value and how many records had a second value. I then wanted to know what percentage the first value was of the total. So there’s a bit of MySQL code that helps make this easy to do.

  SUM(IF(field_name = 'value_one',1,0)) AS 'Value One',
  SUM(IF(field_name = 'value_two',1,0)) AS 'Value Two'
FROM table_name

What this does is counts up how many times value_one and value_two appear in field_name in the table table_name.

You can then take this a step further, if you wanted to, and I did…

you can use a line like this within your query:

This gives you the percentage that value_one is of (value_one + value_two).

Hat tip to this stackoverflow answer by eisberg.

Edit: 2014-05-26-21h53m put the final code snippet into a ‘Gist’ on GitHub.

Short list of software I’m using

Just a quick post of some software that I use, that I’ve just discussed with Seth (he knows who he is).

All useful, but the starting point is better task management, so start with Nozbe. PS: also see remapping the CapsLock key.

Truth, Justice and Coffee

We all want to achieve. We want the truth, we want justice. But above all, we want our coffee. Coffee is the fuel that powers our quest for truth and justice. Let the world know that you are in pursuit of truth, justice and coffee by ordering your own tshirt by clicking here to order yours.

Get your tshirt now. Order today. There are no free steak knives.
Get your tshirt now. Order today. There are no free steak knives, only the deep satisfying feeling that comes from knowing you’ve helped.

PS. I wanted a tshirt, but couldn’t find what I was looking for, so I’ve made it here. If the goal is reached (50 tshirts) at teespring, then they’ll make ’em. Go on, I know you want one, order one for yourself and your neighbour. While you’re at it, get one for your neighbours nephew too.

This offer/campaign ends May 22nd 2014.