2017-06-13 68 views
1

我有一個按星期對結果進行分組的查詢。但是,幾個星期的總數是0,這會拋棄我的圖表。有沒有可能添加一個0周有0評論?按星期計算的SQL組包括星期數,其中count爲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

使用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; 
+0

感謝,試圖運行,但語法錯誤或接近'FROM(SELECT' ... – user2954587

相關問題