tags:

views:

69

answers:

2

I want to group my data by Age and by gender: like this sample data:

Age: 1
      Male: 2
      Female: 3
      Age 1 Total: 5

Age: 2
      Male: 6
      Female: 3
      Age 2 Total: 9

How can I group the data according to age and count all the male and females in that age from mysql database?

+6  A: 
Select age, gender, Count(*) cnt
From your_table
Group By age, gender

will get you

Age  Gender   cnt
  1  Male     2
  1  Female   3
  2  Male     6
  2  Female   9

You should be able to sum the counts per age in PHP afterwards.

Peter Lang
+8  A: 
SELECT
  age,
  SUM(CASE WHEN gender = 'male' THEN 1 ELSE 0 END) males,
  SUM(CASE WHEN gender ='female' THEN 1 ELSE 0 END) females,
  COUNT(*) total
FROM yourtable
GROUP BY age
ceteras
+1 This is the correct answer. Though because the OP is using MySQL, I will shorten that to `Select age, sum(gender ='male') males, sum(gender ='female') females, count(*) total from yourtable a group by age`
Michael Buen
Thanks a lot, a new mysql technique added to my stack..
text
Thanks Michael, that's a really elegant change!
ceteras