我有一个按周分组结果的查询。然而,几个星期以来,总数为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)
答案 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;