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

MySQL Union to make two columns

Ideally, the code below should output the amount of Males in one column and the amount of Females in another. There is no error but it only creates a column for males and puts the amount for both males and females under its column.

SELECT COUNT(Gender) AS Males FROM Customers 
JOIN Rents ON Rents.Customers_Cid= Customers.Cid
JOIN Cars ON Cars.CarId=Rents.Cars_CarId 
WHERE Make='Dodge' AND Gender='M'
UNION 
SELECT COUNT(Gender) AS Females FROM Customers 
JOIN Rents ON Rents.Customers_Cid= Customers.Cid
JOIN Cars ON Cars.CarId=Rents.Cars_CarId 
WHERE Make='Dodge' AND Gender='F';

>Solution :

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

Use conditional aggregation with a single pass query:

SELECT SUM(cu.Gender = 'M') AS Males,
       SUM(cu.Gender = 'F') AS Females
FROM Customers cu
INNER JOIN Rents r ON r.Customers_Cid = cu.Cid
INNER JOIN Cars ON c.CarId = r.Cars_CarId 
WHERE c.Make = 'Dodge';

To make your union approach work, you could just select a computed column for the gender, e.g.

SELECT COUNT(Gender) AS Num, 'M' AS Gender
...
UNION ALL
SELECT COUNT(Gender), 'F'
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