Ask the Expert

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

    Requires Free Membership to View

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


This was first published in March 2003

There are Comments. Add yours.

 
TIP: Want to include a code block in your comment? Use <pre> or <code> tags around the desired text. Ex: <code>insert code</code>

REGISTER or login:

Forgot Password?
By submitting you agree to receive email from TechTarget and its partners. If you reside outside of the United States, you consent to having your personal data transferred to and processed in the United States. Privacy
Sort by: OldestNewest

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: