SQL查询帮助需要在表中加入和计数

时间:2013-02-18 16:13:56

标签: sql select sum

这是我与我的加入相关的第二篇文章。现在我希望有一张表格,其中包含男性和女性的总数......

我有一个名为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练习,但我很感激帮助将这个查询拉到一起。谢谢!

2 个答案:

答案 0 :(得分: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

答案 1 :(得分: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