1

我有 2 个 MySQL 表(用户和评论) - 我想做的是获取一份报告,告诉我有多少用户发表了 1 条评论,有多少用户发表了 2 条评论,有多少用户发表了 3 条评论以及有多少用户发表了 4 条以上评论评论,按月和年分组。

我有这个查询来获取按年/月分组的每个用户发表的评论数

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)

如何修改此查询以提供我想要的结果?

4

2 回答 2

2

再次使用子查询对结果进行分组:

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
于 2013-02-19T16:32:41.267 回答
0

这是一种方法——不确定你是否需要加入 tbluser,但我把它留在那里:

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;

还有一些小提琴样本:http ://sqlfiddle.com/#!3/5fb5c/5

于 2013-02-19T16:34:14.810 回答