簡體   English   中英

sql查詢來計算百分比

[英]sql query to calculate percentage

在下表中,我需要找到處於“紐約”州的男性百分比。

  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 |
+-------+-------+--------+

所需的輸出:

狀態,男性百分比->紐約,75%

紐約市的4人中有3位是男性,而1位是女性。

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

從表中選擇一項)

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

您可以使用子查詢來做到這一點:

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

但是用PHP做到這一點可能更容易,更明智

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

是最簡單的方法。

在sqlite3中工作

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM