1

这是我的第二篇与我的加入有关的帖子。现在我想要一个表格,其中包含男性和女性的计数总和......

我有一个名为 babynames 的表,看起来像这样:

firstname |sex |year |count 
Bob |M| 2010| 150
Bob |M| 2009| 100
Bob |M| 2008| 122
Bob |F| 2007| 2
Bob |F| 2001| 1

我已经能够用这个查询计算出所有男性和女性的婴儿名字

SELECT 
  firstname, sum(count), sex
FROM babynames
GROUP BY firstname
HAVING COUNT(DISTINCT sex) = 2

结果表:

bob|375|M 

这接近我想要的......但是

SELECT 
  firstname, sum(count), sex
FROM babynames GROUP BY firstname, sex

给我结果:

bob|372|M
bob|3|F

现在,我需要两全其美,以便我的表只有性别匹配的名称,理想情况下看起来像这样:

firstname|male count| female count
bob |372|3

虽然我承认我需要一些 SQL 练习,但我会很感激一些帮助将这个查询放在一起。谢谢!!

4

2 回答 2

3
SELECT  firstname,
        SUM(CASE WHEN sex = 'm' THEN count END) MaleCount,
        SUM(CASE WHEN sex = 'f' THEN count END) FemaleCount
FROM    babynames 
GROUP   BY firstname
于 2013-02-18T16:16:57.353 回答
0

尝试这样的事情:

select firstname, sum(malecount) males, sum(femalecount) females
from 
(select 'boys' gender
,firstname
, 0 femalecount
, count(*)  malecount
from babynames
where sex = 'male'
group by 'boys, firstname, 0
union
similar query for girls
) temp
group by firstname
于 2013-02-18T16:21:29.493 回答