gpt4 book ai didi

mysql - 在一个查询中获取两个表字段的计数

转载 作者:行者123 更新时间:2023-11-29 01:22:42 25 4
gpt4 key购买 nike

我正在尝试获取表的性别字段中女性和男性的数量。

有没有办法在一个查询中获取每个的计数?

类似于:

select * from table count(where gender = 'm') as total_males, count(where gender = 'f') as total_females;

还是需要两次查询?

select count(*) from table where gender = 'm';
select count(*) from table where gender = 'f';

最佳答案

这基本上是一个PIVOT。 MySQL 没有数据透视表,因此您可以使用带有 CASE 语句的聚合函数来执行此操作:

select
sum(case when gender = 'm' then 1 else 0 end) Total_Male,
sum(case when gender = 'f' then 1 else 0 end) Total_Female
from yourtable

参见 SQL Fiddle with Demo

或者使用COUNT:

select
count(case when gender = 'm' then 1 else null end) Total_Male,
count(case when gender = 'f' then 1 else null end) Total_Female
from yourtable;

参见 SQL Fiddle with Demo

关于mysql - 在一个查询中获取两个表字段的计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13826969/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com