简体   繁体   English

查询给定数据集中的男女比例#MySQL

[英]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.您可以将COUNT()IF()结合使用来获取性别的计数和比率。

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:假设只有两种可能的性别,此查询可以为您提供总人口中男性的比例,范围为 0 到 1:

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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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