MySQL-计算按国家分组的男性和女性人数
作者:互联网
我有一个带有3列的表格,分别是国家/地区,user_id,性别.
user_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
我已经尝试了许多differnet查询,但是无法在一个查询中返回所有结果,并且如果可能的话,也不想使用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中完成上述操作吗?
谢谢
解决方法:
无需将表与其自身联接.将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
标签:sql,mysql,group-by 来源: https://codeday.me/bug/20191208/2088825.html