mysql—来自同一基础表的两个分组子查询的列之和

lx0bsm1f  于 2021-06-18  发布在  Mysql
关注(0)|答案(1)|浏览(271)

更新我决定了一个更简洁和计算优化的方式来表达这句话。无子查询无多个联接:

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示例数据库,我通过子查询两次查询同一个employees表,并交叉连接结果以获得下面的pivot表。我希望创建一个最后的专栏,将是 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'

我曾尝试再次使用子查询来创建此列,但很明显,我的两个groupby子查询是构建此透视表的错误方法。

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

4smxwvx5

4smxwvx51#

一种更加简洁和计算优化的表达方式。无子查询、无多个联接且易于阅读:

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)

相关问题