【问题标题】:mysql query (fetch number of users based on their activity)mysql查询(根据活动获取用户数)
【发布时间】:2013-02-20 00:34:14
【问题描述】:

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

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

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)

如何修改此查询以获得我想要的结果?

【问题讨论】:

    标签: mysql


    【解决方案1】:

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

    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
    

    【讨论】:

      【解决方案2】:

      这是一种方法——不确定你是否需要加入 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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多