MySQL分组数据

时间:2010-05-07 07:52:43

标签: php sql mysql

我想按年龄和性别对数据进行分组:例如此示例数据:

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

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

如何根据年龄对数据进行分组,并从mysql数据库中计算该年龄段的所有男性和女性?

2 个答案:

答案 0 :(得分:11)

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

答案 1 :(得分:7)

Select age, gender, Count(*) cnt
From your_table
Group By age, gender

会帮你的

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

之后你应该可以在PHP中将每个年龄的计数加起来。