UPDATE I determined a significantly more concise and computationally optimal way of expressing this statement. No subqueries no multiple joins.:
SELECT
month(hire_date) as month,
sum(case when gender ="m" then 1 end) as male,
sum(case when gender ="f" then 1 end) as female,
count(*) as total
FROM employees
GROUP BY MONTH(hire_date)
Using the MySQL Employees Sample Database, I am querying the same employees table twice via subquery and cross joining the results to get the pivot table below. I am looking to create a final column that would be the sum of mcount
and fcount
Month,Gender,mcount,gender,fcount
'1','M','14310','F','9549'
'2','M','14659','F','9789'
'3','M','16200','F','10717'
'4','M','15363','F','10190'
'5','M','15545','F','10398'
'6','M','15000','F','10003'
'7','M','15260','F','10345'
'8','M','15250','F','10146'
'9','M','14632','F','9684'
I have tried to use subqueries again to create this column, but it's making it evident that my two GROUP BY sub-queries are the wrong way to go about building this pivot table.
SELECT mbm.month, mbm.gender, mbm.count as mcount, fbm.gender, fbm.count as fcount
FROM
(SELECT MONTH(hire_date) as Month, gender, COUNT(*) as count
FROM employees
WHERE gender = "M"
GROUP BY gender,MONTH(hire_date)
) as mbm
CROSS JOIN (SELECT MONTH(hire_date) as Month, gender, COUNT(*) as count
FROM employees
WHERE gender = "F"
GROUP BY gender,MONTH(hire_date)
) AS fbm on mbm.Month = fbm.Month