MySQL - 计算按国家/地区分组的男性和女性人数

时间:2011-08-05 10:59:16

标签: mysql sql group-by

我有一个包含3列的表格countryuser_idgenderuser_id只是递增,有许多不同的国家,性别是男性或女性。与此相似

user_id  country  gender
1        japan    male
2        peru     female
3        japan    female
4        fiji     male
5        peru     female

我想运行一个查询来返回一个唯一的国家/地区列表,该国家/地区的user_id总数以及每个国家/地区的男性和女性数字。结果如下:

country total male female
peru    2     NUL  2
japan   2     1    1
fiji    1     1    NUL

我尝试过多个不同的查询,但无法在一个查询中返回所有结果,如果可能,也不想使用2个查询。

这是我的最后一次尝试 - 我知道它很乱,但我正在尝试任何事情:

SELECT DISTINCT a.country AS country, COUNT(b.gender) AS male, COUNT(c.gender) AS     female, COUNT(a.user_id) AS total
  FROM userattributes as a
  LEFT JOIN userattributes as b ON a.user_id=b.user_id
  LEFT JOIN userattributes as c ON a.user_id=c.user_id
  WHERE b.gender='male' AND c.gender='female'
  GROUP BY country;

任何人都可以在一个SELECT中完成上述操作吗?

THX

1 个答案:

答案 0 :(得分:3)

没有必要JOIN表格本身。使用带有CASE聚合的SUM表达式就足够了。

SELECT  country
        , COUNT(*) AS total
        , SUM(CASE WHEN gender = 'male' THEN 1 ELSE 0 END) AS male
        , SUM(CASE WHEN gender = 'female' THEN 1 ELSE 0 END) AS female
FROM    userattributes
GROUP BY
        country