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 QUERY-Calculate the number of students who are male, and the number of students who are female. A student is a person with an enrollment record

I am working on this SQL problem for a class – "Please calculate the number of students who are male, and the number of students who are female. A student is a person with an enrollment record."

The expected result should look like this

Example Result

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

However I have been unable to get the result to return in this format, at this point I am stuck here

enter image description here

Utilizing this code

SELECT 
COUNT(Distinct enrollment.personID) as male
FROM dbo.enrollment
RIGHT JOIN dbo.person ON person.personID=enrollment.personID
WHERE person.gender='male'
UNION
SELECT
COUNT(Distinct enrollment.personID) as female
FROM dbo.enrollment
RIGHT JOIN dbo.person ON person.personID=enrollment.personID
WHERE person.gender='female'; 

Any help getting me pointed towards the correct format would be greatly appreciated.

>Solution :

Actually using a UNION running two separate queries to obtain male and female counts.
To get what you need, You have to use conditional aggregation with a CASE statement, in just one single query. Which can be more efficient and reduces the need for two separate queries:

SELECT
  COUNT(DISTINCT CASE WHEN person.gender = 'male' THEN enrollment.personID END) as male,
  COUNT(DISTINCT CASE WHEN person.gender = 'female' THEN enrollment.personID END) as female
FROM dbo.enrollment
RIGHT JOIN dbo.person ON person.personID = enrollment.personID;

Another more readable and easy way to solve it with subquery:

SELECT SUM(p.gender = 'male') AS male, SUM(p.gender = 'female') AS female
FROM person AS p
WHERE p.personID IN (SELECT personID FROM enrollment);
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