mysql查询(根据用户的活动获取用户数)

时间:2013-02-19 16:20:23

标签: mysql

我有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)

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

2 个答案:

答案 0 :(得分: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

答案 1 :(得分: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