按周计算多个列数

时间:2012-12-06 14:58:31

标签: mysql sql

我有以下两个表:

帖子

  • 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)

如何添加评论计数?

2 个答案:

答案 0 :(得分:3)

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

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

答案 1 :(得分:0)

以下是一种使用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,也要保持数周。我之所以不加入这些表的原因是因为,据推测,您想要在评论日期之前报告,而不是与评论相关联的帖子的发布日期。