每周SQL组包括计数为0的周数

时间:2017-06-13 21:43:45

标签: sql postgresql

我有一个按周分组结果的查询。然而,几个星期以来,总数为0,这会抛出我的图表。是否可以在0周内添加0,有0条评论?

SELECT COUNT(*) AS total, 
DATE_TRUNC('week', created_at) AS week FROM "reviews" 
GROUP BY DATE_TRUNC('week', created_at) 
ORDER BY DATE_TRUNC('week', created_at)

1 个答案:

答案 0 :(得分:1)

使用generate_series()

SELECT w.week, COUNT(*) AS total
FROM (SELECT generate_series(min(DATE_TRUNC('week', created_at)),
                             max(DATE_TRUNC('week', created_at)),
                             interval '7 day'
                            ) as week
      FROM reviews
     ) w LEFT JOIN
     "reviews" 
     ON DATE_TRUNC('week', created_at) = w.week
GROUP BY w.week
ORDER BY w.week;