Reputation: 691
I have 2 MySQL tables (user and comments) - what I want to do is fetch a report that gives me how many users made 1 comment, how many users made 2 comments, how many users made 3 comments and how many users made 4+ comments, grouped by month and year.
I have this query to get the number of comments made by each user grouped by year/month
select year(c.datecreated) as comment_year, month(c.datecreated) as comment_month,
count(c.id) as num_comments
from tblcomments c
inner join tbluser u on u.id = c.userid
where
c.datecreated <= '2013-02-19' and c.datecreated >= '2012-03-01'
group by c.userid, year(c.datecreated), month(c.datecreated)
How do I modify this query to give me the results I want?
Upvotes: 1
Views: 81
Reputation: 62861
Here is one way to do it -- not sure you need to join on the tbluser, but I left it there:
SELECT comment_year, comment_month,
COUNT(userId) userCnt,
Num_Comments
FROM (
select
year(c.datecreated) as comment_year,
month(c.datecreated) as comment_month,
c.userid,
CASE WHEN count(c.id) >= 4 THEN '4+' ELSE CAST(COUNT(c.id) as varchar) END as num_comments
from tblcomments c
inner join tbluser u on u.id = c.userid
where
c.datecreated <= '2013-02-19' and c.datecreated >= '2012-03-01'
group by c.userid, year(c.datecreated), month(c.datecreated)
) t
GROUP BY comment_year, comment_month, Num_Comments;
And some sample fiddle: http://sqlfiddle.com/#!3/5fb5c/5
Upvotes: 0
Reputation: 126025
Use a subquery to group your results a second time:
SELECT ym,
SUM(c = 1) AS `num_1`,
SUM(c = 2) AS `num_2`,
SUM(c = 3) AS `num_3`,
SUM(c>= 4) AS `num_4+`
FROM (
SELECT DATE_FORMAT(datecreated, '%Y-%m') AS ym, COUNT(*) AS c
FROM tblcomments
WHERE datecreated BETWEEN '2012-03-01' AND '2013-02-19'
GROUP BY ym, userid
) t
GROUP BY ym
Upvotes: 2