Q

Count males and females as well as total

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.
 

This was first published in March 2003

Dig deeper on Oracle and SQL

Pro+

Features

Enjoy the benefits of Pro+ membership, learn more and join.

Have a question for an expert?

Please add a title for your question

Get answers from a TechTarget expert on whatever's puzzling you.

You will be able to add details on the next page.

0 comments

Oldest 

Forgot Password?

No problem! Submit your e-mail address below. We'll send you an email containing your password.

Your password has been sent to:

-ADS BY GOOGLE

SearchDataManagement

SearchBusinessAnalytics

SearchSAP

SearchSQLServer

TheServerSide

SearchDataCenter

SearchContentManagement

SearchFinancialApplications

Close