2017-04-15 62 views
0

我必須以每個單元中的男性數量,女性數量來顯示摘要。請嘗試以下查詢:MySQL GROUP BY沒有給出想要的結果

SELECT 
    unit, 
    CASE gender 
     WHEN 'Male' THEN COUNT(id) 
    END AS 'male', 
    CASE 
     WHEN gender = 'Female' THEN COUNT(id) 
    END AS 'female' 
FROM 
    admission_info 
WHERE 
    admission_date = '2017-04-15' 
GROUP BY gender 

下面是顯示輸出的Fiddle。但我想在1行中顯示單位名稱,男性人數,女性人數。

+0

由單元組,而不是性別 –

回答

5
SELECT unit, 
sum(CASE gender WHEN 'Male' THEN 1 else 0 END) AS 'male', 
sum(CASE WHEN gender='Female' THEN 1 else 0 END) AS 'female' 
FROM admission_info WHERE admission_date='2017-04-15' 
group by unit 
+0

PERFECT輸出。謝謝。 – sunny93

+0

在最後添加GROUP BY單元,否則它始終返回1行,無論單位是A還是B. – sunny93

1
SELECT unit, gender, count(id) as count 
FROM admission_info WHERE admission_date='2017-04-15' GROUP BY unit, gender 
+0

它返回2行 – sunny93

+0

是的,你有什麼期待做? @ sunny93 – wajeeh

+0

期望的輸出是在問題... –