MySQL GROUP BY没有给出想要的结果

时间:2017-04-15 04:45:02

标签: mysql sql

我必须将摘要显示为男性人数,每个单位的女性人数。尝试了以下查询:

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。但我希望它在一行中显示单位名称,男性人数,女性人数。

2 个答案:

答案 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

答案 1 :(得分:1)

$onInit()