sql查询来计算百分比

时间:2015-07-30 09:49:59

标签: mysql sql

在下表中,我需要找到处于州内的男性百分比'。

  select count(*) from table where state = 'nyc' and gender = 'male';

给了我来自纽约的男性人数。我需要来自纽约市的男性比例为75%。

+-------+-------+--------+
| name  | state | gender |
+-------+-------+--------+
| Jon   | nyc   | male   |
+-------+-------+--------+
| obama | LA    | male   |
+-------+-------+--------+
| kat   | nyc   | male   |
+-------+-------+--------+
| andy  | nyc   | male   |
+-------+-------+--------+
| sri   | nyc   | female |
+-------+-------+--------+

期望的输出:

state,male_percentage - >纽约,75%

3为男性,1为女性,总数为4,来自纽约。

4 个答案:

答案 0 :(得分:1)

select count(*)/(select count(*) from table where gender='male')*100
from table where state = 'nyc' and gender = 'male';

答案 1 :(得分:1)

从表中选择一个

 select state ,100 * sum( IF(gender = 'male',1,0) ) / count(*) 
    from table where state = 'nyc' 
    group by state 

答案 2 :(得分:0)

您可以使用子查询执行此操作:

(select count(*) from table where gender='male' and state = 'nyc')/
(select count(*) from table where state = 'nyc') *100;

但它可以更容易,更明智的恕我直言,在PHP中做到这一点

答案 3 :(得分:0)

select (select count(*) from table where state='nyc' and gender='male') * 100.0 / count(*)
from table

是最简单的方法。

适用于sqlite3