【问题标题】:Multiple column counts by week每周多列计数
【发布时间】:2012-12-06 14:58:31
【问题描述】:

我有以下两张表:

帖子

  • post_id
  • post_title
  • post_timestamp

评论

  • comment_id
  • posts_post_id
  • comment_content
  • comment_timestamp

我想创建一个显示每周发帖数和评论数的报告。像这样的:

Week    StartDate      Posts     Comments
1       1/1/2012       100        305
2       1/8/2012       115        412

我有这个查询,但它只从 Posts 表中提取。

select makedate( left(yearweek(p.post_timestamp),1),week(p.post_timestamp, 2 ) * 7 ) as Week, COUNT(p.post_id) as Posts  
FROM cl_posts p
GROUP BY Week
ORDER BY WEEK(p.post_timestamp)

如何添加评论计数?

【问题讨论】:

    标签: mysql sql


    【解决方案1】:

    我认为你需要这样的东西:

    select
      week(post_timestamp) as Week,
      adddate(date(post_timestamp), INTERVAL 1-DAYOFWEEK(post_timestamp) DAY) as StartDate,
      count(distinct post_id),
      count(comment_id)
    from
      posts left join comments
      on comments.posts_post_id = posts.post_id
    group by Week, StartDate
    

    【讨论】:

    • 干净简单。像魅力一样工作!
    【解决方案2】:

    这是一种方法,使用join

    select coalesce(p.week, c.week) as week, p.Posts, c.Comments
    from (select makedate( left(yearweek(p.post_timestamp),1),week(p.post_timestamp, 2 ) * 7 ) as Week,   
                 COUNT(*) as Posts  
          FROM cl_posts p
          GROUP BY Week
         ) p full outer join
         (select makedate( left(yearweek(c.comment_timestamp),1),week(c.comment_timestamp, 2 ) * 7 ) as Week,   
                 COUNT(*) as Comments
          FROM cl_comments c
          GROUP BY Week
         ) c
         on p.week = c.week
    order by 1 
    

    我使用 full outer join 而不是另一种连接类型的原因是即使其中一个或其他计数为 0 也能保持数周。我没有将表连接在一起的原因大概是因为您想要评论日期的报告,而不是与评论相关的帖子的发布日期。

    【讨论】:

    • 我对 COALESCE 和 SUB-QUERIES 的工作不多,所以我想试试你的查询。但是,查询没有正确计算 cmets。知道为什么吗?此外,MySQL 不支持 FULL OUTER JOINS。
    • 是的。我使用 post_timestamp 而不是 comment_timestamp 来表达你一周的部分表达。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-03
    • 1970-01-01
    相关资源
    最近更新 更多