Skip to content
Advertisement

Arithmetic operation on the subsets of results from a SQL groupby statement

I have a schema with sex(m/f),state_name(all states of a country), student_name,and education (phd,ms). I use following query to return total males or females in each category of education for every state.

select sex,education,count(*) from mytable group by education,sex;

How can I write a query that returns the arithmetic ratio of (male divided by female) for each education in every state?

I am trying to get to query that gives me gender ratio across education tiers for each state (I got count above, but I could not figure out how to do arithmetic division)

Advertisement

Answer

You can do conditional aggregation:

select education, sum(sex = 'male') / nullif(sum(sex = 'female'), 0) ratio
from mytable
group by education
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement