【问题标题】:i want to count total number of males and females from the result of sub query. Is there any mysql query我想从子查询的结果中计算男性和女性的总数。有没有mysql查询
【发布时间】:2020-03-18 05:07:02
【问题描述】:
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

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

有没有这样的mysql查询?

谢谢

【问题讨论】:

    标签: mysql


    【解决方案1】:

    使用聚合

    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"
    

    【讨论】:

    • 你能帮我把这个输出加入到我之前的查询结果中吗(即)输出应该是带有数据/列的表...名称、性别、总数、女性、男性
    【解决方案2】:
    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'
    

    【讨论】:

    • 你能帮我把这个输出加入到我之前的查询结果中吗(即输出应该是带有数据/列的表...名称、性别、总数、女性、男性。
    • 你使用的是什么版本的 MySQL?
    • PHP 我的管理员,版本低于 8.0
    • 在这种情况下,我会运行 2 个单独的查询。
    猜你喜欢
    • 2013-06-11
    • 1970-01-01
    • 2022-01-11
    • 1970-01-01
    • 1970-01-01
    • 2022-01-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多