我有一个表tb_user,其中的记录如下:
Name gender location grewup
Arun male india britain
sonia female USA dubai
sheetal female india Russia
我想要做的是根据位置获取记录:
Location Total Count Female Male
United States 50 30 20
Canada 30 17 13
Lebanon 20 10 10
Germany 10 2 8
France 5 2 3
select `Location`, COUNT(id) as totalcount,(select COUNT(id) from tb_user where `gender` = 'Female') as female,(select COUNT(id) from tb_user where `gender` = 'Male') as male FROM tb_user GROUP BY `Location`
我在这里使用了上述查询我得到了来自不同国家的用户的总数,满足一个条件,即总数,但我也想要女性和男性候选人的数量,但这个查询提供了总数每排男性和女性。
答案 0 :(得分:0)
SELECT * FROM
(SELECT location,COUNT(id)as totalcount 来自tb_user GROUP BY位置)作为foobar
天然加入
(选择位置,COUNT(id)为女性 来自tb_user GROUP BY位置,性别 性别='女性')为foo
天然加入
(选择位置,COUNT(id)为男性 来自tb_user GROUP BY位置,性别 性别='男性')为吧
希望它有效
答案 1 :(得分:0)
我已经解决了这个问题, 对于需要回答此查询的用户,请执行以下操作:
select `Location`, COUNT(id) as totalcount, sum(IF(`gender` = 'Female',1,0)) as female,sum(IF(`gender` = 'Male',1,0)) as male FROM tb_user GROUP BY `Location`