Is it possible to do something like this:
select count(*) as total, count(gender where gender = 'male') as male, count(gender where gender = 'female') as female from mytable
Output something like this:
total male female 100 75 25
Yes, and you were so close!
select count(*) as total , sum( case when gender = 'male' then 1 else 0 end ) as male , sum( case when gender = 'female' then 1 else 0 end ) as female from mytable
The idea here is that for each row, the value of the gender field is tested twice, once for male and once for female, and a 1 is summed into the appropriate total for whichever gender it is, and a 0 for the other. Note that it's a sum of 1's and 0's, not a count, that gives the total for each gender.
There's no guarantee in the query itself that the male and female totals will equal the number of rows. The assumption is that male and female are the only values. If there's a row with a null gender, or some other value, then the totals won't add up.
For More Information
- Dozens more answers to tough SQL questions from Rudy Limeback.
- The Best SQL Web Links: tips, tutorials, scripts, and more.
- Have an SQL tip to offer your fellow DBAs and developers? The best tips submitted will receive a cool prize. Submit your tip today!
- Ask your technical SQL questions -- or help out your peers by answering them -- in our live discussion forums.
- Ask the Experts yourself: Our SQL, database design, Oracle, SQL Server, DB2, metadata, object-oriented and data warehousing gurus are waiting to answer your toughest questions.
This was first published in March 2003