Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/mysql/56.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何直接从MySQL查询中获取两个总和的百分比?_Mysql - Fatal编程技术网

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

如何直接从MySQL查询中获取两个总和的百分比?,mysql,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中计算百分比。但我想知道,有没有办法直接从查询中获取百分比 SELECT sum(case when `ge

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

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中计算百分比。但我想知道,有没有办法直接从查询中获取百分比

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

有没有办法在计算前检查以避免div为零?