使用子查询(MySQL)时分组的替代方法?

时间:2011-11-07 00:36:11

标签: mysql charts grouping

我正在尝试创建一个相对复杂的MySQL查询来生成堆积条形图 - 按部门按月计算请求数。

我一直试图使用的方法是通过子查询 - 但它似乎是一个死胡同,因为按月分组不适用于子查询。它为返回的每一行重复相同的总计数,例如

MONTH     HR    ACCT  CUST SVC
October   5     1     5
November  5     1     5
December  5     1     5

以下是我正在使用的查询:

SELECT 
MONTH(request.submissiondate), YEAR(request.submissiondate),
(SELECT count(*) from request where request.DEPARTMENTID='1') as 'Human Resources',
(SELECT count(*) from request where request.DEPARTMENTID='2') as 'Accounting',
(SELECT count(*) from request where request.DEPARTMENTID='3') as 'Customer Service'

FROM request 
WHERE YEAR(request.submissiondate) = 2011
group by MONTH(request.submissiondate), YEAR(request.submissiondate)

希望有一种相对简单的替代方法,我只是缺席。

提前感谢您的帮助!

1 个答案:

答案 0 :(得分:1)

也许这样的事情可行吗?

SELECT 
MONTH(request.submissiondate), YEAR(request.submissiondate), request.DEPARTMENTID, COUNT(*) as 'total'
FROM request 
WHERE YEAR(request.submissiondate) = 2011
group by MONTH(request.submissiondate), YEAR(request.submissiondate), request.DEPARTMENTID
ORDER BY request.submissiondate 

我不知道是否有可能获得上面列出的输出,但是你应该能够遍历返回的行并使用你正在使用的服务器端语言重新排列输出。