我首先使用以下查询计算数据库中男性和女性的百分比:
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
, 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