Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

SQL: Displaying counts in a column for diff values in same row

I have a table ‘patients’ which has a column ‘gender’. I want to show number of males and females in 2 columns side-by-side. I do it as:

Select * from 
(SELECT count(gender) AS male_count from patients
GROUP BY gender
having gender = 'M')
CROSS JOIN
(SELECT count(gender) as female_count from patients
GROUP BY gender
having gender = 'F')

It works, but I am doing SELECT two times. I guess there is a better way of achieving this.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

An aggregated conditional case expression should be all you need

select 
    Sum(case when gender='M' then 1 end) Male_Count,
    Sum(case when gender='F' then 1 end) Female_Count
from patients;
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading