使用子查询(MySQL)时分组的替代方案?
我正在尝试创建一个相对复杂的 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)
希望有一个我只是缺少的相对简单的替代方法。
预先感谢您的帮助!
I'm trying to create a relatively complex MySQL query to generate a stacked bar chart - count of requests by month, by department.
The approach I've been trying to use is via sub-query -- but it seems to be a dead end since the grouping by month doesn't apply in the subquery. It repeats the same total count for each row returned, e.g.
MONTH HR ACCT CUST SVC
October 5 1 5
November 5 1 5
December 5 1 5
Here is the query I'm using:
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)
Hoping there's a relatively simple alternative approach that I'm just missing.
Thanks in advance for your help!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
也许这样的东西会起作用?
我不知道是否可以准确地获得上面列出的输出,但是您应该能够循环返回的行并使用您使用的任何服务器端语言重新排列输出。
Maybe something like this would work?
I don't know if it's possible to get exactly the output as you listed above, but you should be able to loop through the returned rows and rearrange the output with whatever server-side lamguage you are using.