在 MySQL / SQL 中获取同一行的条件计数
假设我有一个表 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
我如何构建查询以使它们出现在同一行?
IE,
Team | Males | Females
A | 1 | 1
B | 2 | 1
Suppose I have a table, Foo, that looks like this:
ID | Name | Gender | Team
1 | Bob | Male | A
2 | Amy | Female | A
3 | Cat | Female | B
4 | Dave | Male | B
5 | Evan | Male | B
If I wanted to get a list of the number of males and females per team on the same row, how would I do that?
I know I could do SELECT COUNT(Name) as "#", Team, Gender FROM foo GROUP BY Team, Gender
, and that's fine for most purpose.
But that would give me 2 rows per team, like below, and that can be a pain.
# Team Gender
1 | A | Male
1 | A | Female
1 | B | Female
2 | B | Male
How could I structure the query such that they appear on the same row?
ie,
Team | Males | Females
A | 1 | 1
B | 2 | 1
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
对于评论
你很接近。答案是
For the comment
You're close. The answer is
我正在寻找的模式是自连接;在我看来,语法和逻辑比 CASE 模式更优雅。
具体来说,
我想要在不同列中进行的分组不是 case 语句,而是被拆分为同一个表的自己的副本。然后,您将男性玩家表与团队中的女性玩家表合并,然后按团队进行分组。
The pattern I was looking for was a Self-Join; the syntax and logic is, in my mind, more elegant then the CASE pattern.
Specifically,
Instead of case statements, the groupings I want in different columns get split into their own copies of the same table. You then join the table of Male players with a Table of Female players on the Team, and then group by the Team.