mysql - 在 MySQL/SQL 中对同一行进行条件计数

标签 mysql sql group-by

假设我有一张 table ,Foo,它看起来像这样:

ID  | Name  | Gender  | Team
1   | Bob   | Male    | A
2   | Amy   | Female  | A
3   | Cat   | Female  | B
4   | Dave  | Male    | B
5   | Evan  | Male    | B

如果我想获取在同一行的每个团队的男性和女性人数列表,我该怎么做?

我知道我可以SELECT COUNT(Name) as "#", Team, Gender FROM foo GROUP BY Team, Gender,这对大多数用途来说都很好。

但这会给我每个团队 2 行,如下所示,这可能会很痛苦。

#  Team Gender
1 | A | Male
1 | A | Female
1 | B | Female
2 | B | Male

如何构造查询以使它们出现在同一行?

即,

Team | Males | Females
A    |   1   | 1
B    |   2   | 1

最佳答案

select team,
 SUM(case when gender='Male' then 1 else 0 end) Male,
 SUM(case when gender='Female' then 1 else 0 end) Female
from tbl
group by team

评论

Imagine now that each row has an arbitrary numeric score associated with it, in a Score column. How would I have 'Male points' and 'Female points? Would that be SUM(case when gender="male" then select points else 0 end) "Male Points"

你很接近。答案是

select team,
 SUM(case when gender='Male' then 1 else 0 end) Male,
 SUM(case when gender='Male' then points else 0 end) `Male Points`,
 SUM(case when gender='Female' then 1 else 0 end) Female,
 SUM(case when gender='Female' then points else 0 end) `Female Points`
from tbl
group by team

关于mysql - 在 MySQL/SQL 中对同一行进行条件计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5098352/

相关文章:

php - 试图删除我的表格中显示的数据

MySQL - 让 ORDER BY 按嵌入到字符串字段中的数字排序

php - 当服务器的使用量超过限制时将用户重定向到静态页面

group-by - 在HBase中按分组

sql-server - 模仿 group_concat() 与 GROUP BY 结合

mysql - 在 xampp 上创建新数据库

SQL Server ALTER 字段 NOT NULL 需要永远

SQL 查询以查找所有可能的路径

sql - 清理VB中的文本字符串

mysql - 在 GROUP BY 中使用 LIMIT 来获得每组 N 个结果?