如何直接从MySQL查询获得两个总和的百分比?

时间:2013-01-20 20:39:55

标签: mysql

我首先使用此查询计算数据库中男性和女性的百分比:

SELECT sum(case when `gender` = 'M' then 1 else 0 end) as male
     , sum(case when `gender` = 'F' then 1 else 0 end) as female
FROM userinfo 
WHERE id in (10,1,5)

然后在php中我计算百分比。但我想知道,有没有办法直接从查询中获得百分比?

1 个答案:

答案 0 :(得分:2)

SELECT sum(case when `gender` = 'M' then 1 else 0 end) as male
     , 100*sum(case when `gender` = 'M' then 1 else 0 end)/count(*) as malepct
     , sum(case when `gender` = 'F' then 1 else 0 end) as female
     , 100*sum(case when `gender` = 'F' then 1 else 0 end)/count(*) as femalepct
FROM userinfo 
WHERE id in (10,1,5)

...假设你没有在空行集上运行(除以零)

如果你是想要将无效(除以零)值替换为-1使用

if(ifnull(count(*),0)>0,100*sum(case when `gender` = 'M' then 1 else 0 end)/count(*),-1) as malepct