Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 General SQL Server Forums
 New to SQL Server Programming
 Query with Count and group by

Author  Topic 

DaveBF
Yak Posting Veteran

89 Posts

Posted - 2013-11-19 : 11:41:49
I have a table of people:
Name, City, Sex
I want a table where each line is the city, and the number of Males and Females.

For example, this is what I tried, and I know it's wrong:


Select City, count(name) where Sex = 'M' as NumberM,
count(name) where Sex = 'F' as NumberF
Group by City


how do I do this?
Thanks.

TG
Master Smack Fu Yak Hacker

6065 Posts

Posted - 2013-11-19 : 12:03:33
Here's one way:

Select City
,sum(case when sex = 'm' then 1 else 0 end) as NumberM
,sum(case when sex = 'f' then 1 else 0 end) as NumberF
Group by City


Be One with the Optimizer
TG
Go to Top of Page

DaveBF
Yak Posting Veteran

89 Posts

Posted - 2013-11-19 : 12:09:07
quote:
Originally posted by TG

Here's one way:

Select City
,sum(case when sex = 'm' then 1 else 0 end) as NumberM
,sum(case when sex = 'f' then 1 else 0 end) as NumberF
Group by City


Be One with the Optimizer
TG


Got it. Thanks!
Go to Top of Page

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2013-11-20 : 02:02:23
Another way is to use pivot


select City,[m] AS NumberM,[f] AS NumberF
from (select City,sex,1 as cnt
from table
)m
pivot (sum(cnt) for sex in ([m],[f]))p


------------------------------------------------------------------------------------------------------
SQL Server MVP
http://visakhm.blogspot.com/
https://www.facebook.com/VmBlogs
Go to Top of Page
   

- Advertisement -