all groups > sql server programming > november 2003 >
You're in the

sql server programming

group:

Help with 'group by' SQL Query



Re: Help with 'group by' SQL Query Aaron Bertrand [MVP]
11/30/2003 1:09:38 PM
sql server programming: Maybe try this?

SELECT school, schoolyear, class, gender,
MALE = SUM(CASE WHEN gender='MALE' THEN 1 ELSE 0 END),
FEMALE = SUM(CASE WHEN gender='FEMALE' THEN 1 ELSE 0 END)
GROUP BY school, schoolyear, class, gender

--
Aaron Bertrand
SQL Server MVP
http://www.aspfaq.com/




[quoted text, click to view]

Re: Help with 'group by' SQL Query Aaron Bertrand [MVP]
11/30/2003 1:10:27 PM
Sorry, little booboo, just copied the other columns. Should look like this.

SELECT school, schoolyear, class,
MALE = SUM(CASE WHEN gender='MALE' THEN 1 ELSE 0 END),
FEMALE = SUM(CASE WHEN gender='FEMALE' THEN 1 ELSE 0 END)
GROUP BY school, schoolyear, class

--
Aaron Bertrand
SQL Server MVP
http://www.aspfaq.com/




[quoted text, click to view]

Help with 'group by' SQL Query Adrian
11/30/2003 5:55:23 PM
Using the following query (hopefully it is self-explanatory):

select school, schoolyear,class, gender, count(gender)
from schools
group by school, schoolyear,class, gender

This gives two rows for each class, one for males, one for females. For
example:

SchoolOne, YearOne, ClassOne, Male,10
SchoolOne, YearOne, ClassOne, Female,15

What I would like is to have just one row for each class, giving the count
of males and females, like:

SchoolOne, YearOne, ClassOne,10,15

I would be grateful for any help.

Adrian




Re: Help with 'group by' SQL Query David Portas
11/30/2003 6:13:16 PM
SELECT school, schoolyear, class,
COUNT(CASE gender WHEN 'male' THEN 1 END) AS male,
COUNT(CASE gender WHEN 'female' THEN 1 END) AS female
FROM schools
GROUP BY school, schoolyear, class

--
David Portas
------------
Please reply only to the newsgroup
--

Re: Help with 'group by' SQL Query Adrian
11/30/2003 8:19:42 PM
Aaron and David,

Thanks very much. They both work nicely.

Adrian


[quoted text, click to view]

AddThis Social Bookmark Button