MySQL data grouping

I want to group my data by age and gender: for example, 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 data according to age and count all men and women at that age from mysql database?

+2


a source to share


2 answers


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

      



+11


a source


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 will then be able to sum up age scores in PHP.

+7


a source







All Articles