简体   繁体   中英

query for male to female ratio in the given dataset #MySQL

how to write query for male to female ratio of the given dataset

select gender
     , 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 adult;

this gives separate count but no ratio.

You can use COUNT() in combination with IF() to get the counts and ratio of the gender.

Example table content:

+----+-------+--------+
| id | name  | gender |
+----+-------+--------+
|  1 | John  | male   |
|  2 | Jane  | female |
|  3 | Stacy | female |
|  4 | Karen | female |
|  5 | Bob   | male   |
+----+-------+--------+

With the following query:

SELECT
    COUNT(IF(gender = 'male', 1, NULL)) count_male,
    COUNT(IF(gender = 'female', 1, NULL)) count_female,
    COUNT(IF(gender = 'male', 1, NULL))/COUNT(IF(gender = 'female', 1, NULL)) as ratio
FROM
    users;

you will get the following result:

+------------+--------------+--------+
| count_male | count_female | ratio  |
+------------+--------------+--------+
|          2 |            3 | 0.6667 |
+------------+--------------+--------+

Assuming that there are only two possible genders, this query can give you the ratio of males within the total population, on a 0 to 1 scale:

select avg(gender = 'male') ration from adult;

And here is the ratio of females:

select avg(gender = 'female') ration from adult;

If you are looking for the ratio of females to males, then:

select sum(gender = 'female') / nullif(sum(gender = 'male'), 0) from adult;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM