缺少日期的PostgreSQL聚合

时间:2015-05-21 16:20:43

标签: sql postgresql select aggregate-functions

我正在尝试此查询

@Override
protected void paintComponent(Graphics g) {
g.setColor(Color.BLACK);
[..]
}

然后返回

SELECT date_trunc('day', commit_at) AS day, count(*)
  FROM commits
  GROUP BY date_trunc('day', commit_at)
  ORDER BY date_trunc('day', commit_at) ASC;

问题是:我如何强迫空天出现在结果中?

      day         | count 
---------------------+-------
2015-05-18 00:00:00 |     5
2015-05-19 00:00:00 |     2
2015-05-21 00:00:00 |     2
(3 lignes)

1 个答案:

答案 0 :(得分:4)

这样做的一种方法是使用nu generate_series生成最小日期和最大日期之间的所有日期,然后将其加入到聚合查询中:

SELECT    DATE_TRUNC ('day', 
                      GENERATE_SERIES (MIN(commit_at), MAX(commit_at), '1 day') 
             AS day, 
          COALESCE (cnt, 0)
FROM      commits
LEFT JOIN (SELECT   DATE_TRUNC('day', commit_at) AS cday
           FROM     commits
           GROUP BY DATE_TRUNC('day', commit_at)) agg ON day = cday
ORDER BY  1 ASC