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!
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.