简体   繁体   中英

MySQL GROUP BY not giving desired result

I have to show summary as number of males, number of females in each unit. Tried the following query:

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

Here's the Fiddle which shows the output. But i want it in 1 row where it should show unit name, number of males, number of females.

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
SELECT unit, gender, count(id) as count
FROM admission_info WHERE admission_date='2017-04-15' GROUP BY unit, gender

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM