更新 我确定了一种表达该语句的更为简洁和优化的方式。没有子查询,没有多个联接。
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)
使用MySQL Employees Sample Database,我通过子查询两次查询相同的employee表,并将结果交叉联接以获取下面的数据透视表。我希望创建一个最终的列,该列将是mcount
和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'
我试图再次使用子查询来创建此列,但是很明显,我的两个GROUP BY子查询是构建此数据透视表的错误方法。
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
答案 0 :(得分:0)
一种表达该语句的更为简洁和计算最佳的方式。没有子查询,没有多个联接,并且易于阅读:
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)