2014-01-30 80 views
0

我創建了這樣的總結初始列的MySQL

"select count(if(gender="male",1,null)) as malecount, 
    count(if(gender="female",1,null)) as femalecount from biodata" 

這是工作的查詢,而我想總結一下算這樣的:

"select count(if(gender="male",1,null)) as malecount, 
    count(if(gender="female",1,null)) as femalecount, male+female as sumgender 
    from biodata" 

ofcourse該查詢將有助於當我做if語句中的條件很多

請幫我解決這種情況...

回答

0

寫這種方式來解決問題

select malecount+femalecount as sumcount from (select 
count(if(gender="male",1,null)) as malecount, 
count(if(gender="female",1,null)) as femalecount from biodata) as 
query 
0

select 
count(if(gender="male",1,null)) as malecount, 
count(if(gender="female",1,null)) as femalecount, 
count(if(gender in ("female","male",1,0)) as sumgender 
from biodata 

,或者如果你是確保所有行都具有男性或女性的性別,用一個簡單的計數(1)

select 
count(if(gender="male",1,null)) as malecount, 
count(if(gender="female",1,null)) as femalecount, 
count(1) as sumgender 
from biodata 

或者做一個子查詢

select 
malecount, 
femalecount, 
malecount + femalecount as sumgender 
from (
select 
count(if(gender="male",1,null)) as malecount, 
count(if(gender="female",1,null)) as femalecount 
from biodata 
) sub 

但你不能使用聚合別名來計算在同一個選擇。