繁体   English   中英

我想从子查询的结果中计算男性和女性的总数。 有没有mysql查询

[英]i want to count total number of males and females from the result of sub query. Is there any mysql query

SELECT name,gender FROM table1 INNER JOIN table2 ON table1.id = table2.form_id WHERE table1.city ="Banglore";

上面的查询显示了位于班格罗尔的人的姓名和性别。

   Name      Gender
 ___________________
   Riya      Female 
   Ramesh    Male
   Anand     Male
   preety    Female
   Rakesh    Male

现在我想从上面的查询结果中统计记录总数、男性总数和女性总数。 (即)Output 应该是带有数据的表(姓名、性别、total_count = 5、total_males = 3、total_females = 2)。

有没有这样的 mysql 查询?

谢谢

使用聚合

select count(*), count(case when gender='Male' then 1 end) as MaleCount,
count(case when gender='Female' then 1 end) as femalecount
FROM table1 INNER JOIN table2 ON table1.id = table2.form_id 
WHERE table1.city ="Banglore"
select count(*) as total,
       sum(gender = 'Female') as females,
       sum(gender = 'Male') as males
FROM table1 
INNER JOIN table2 ON table1.id = table2.form_id 
WHERE table1.city = 'Banglore'

如果你想把所有这些放在一起,这对于版本低于 8.0 的 MySQL 来说将是一个丑陋的查询。 但是使用 MySQL 8+ 你可以简单地做

select name, gender, 
       count(*) over() as total,
       sum(gender = 'Male') over() as males,
       sum(gender = 'Female') over() as females
FROM table1 
INNER JOIN table2 ON table1.id = table2.form_id 
WHERE table1.city = 'Banglore'

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM