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.
Dig deeper on Oracle and SQL
Have a question for an expert?
Please add a title for your question
Get answers from a TechTarget expert on whatever's puzzling you.