获取条件指向MySQL / SQL中的同一行

时间:2011-02-23 22:58:25

标签: mysql sql group-by

假设我有一个表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

2 个答案:

答案 0 :(得分:5)

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

评论

  

现在想象一下,在每一行中,每一行都有一个与之关联的任意数字分数。我怎么会有'男性积分'和'女性积分?那是SUM(性别=“男性”的情况,然后选择其他0结束点)“男性点数”

你很亲密。答案是

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

答案 1 :(得分:1)

我寻找的模式是自我加入;在我看来,语法和逻辑比CASE模式更优雅。

具体地,

SELECT Males.Team, COUNT(Males.id) as "Males", SUM(Males.Points) as "Male Points", 
       COUNT(Females.id) as "Females", SUM(Females.Points) as "Female Points" 
FROM scores as Males 
LEFT JOIN scores as Females ON Males.Team=Females.Team AND Females.Gender="Female" 
WHERE Males.Gender="Male" 
GROUP BY Team

而不是case语句,我想要在不同列中的分组被分成他们自己的同一个表的副本。然后,您可以在团队中加入男性玩家表和女性玩家表,然后由团队分组。