2013-01-20 208 views
0

林計算首先使用此查詢男人和女人在我的數據庫的百分比:如何直接從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我計算百分比。但是我想知道,有沒有辦法直接從查詢中獲得百分比?

回答

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

有沒有辦法在計算之前檢查以避免div被零? – DomingoSL

+0

@DomingoSL編輯了我的答案。 –