不匹配时包含来自 cte 的值

Include value from cte when it has not match

在我的 table 中,我有一些条目 - 在 table 的日期列 - 不早于 2016-01-04(2016 年 1 月 4 日)。 现在我想做一个查询,它或多或少地计算具有特定日期值的行数,但我希望这个查询能够 return [=] 中不存在的日期的 0 计数26=].

我有这个:

with date_count as (select '2016-01-01'::date + CAST(offs || ' days' as
interval) as date from generate_series(0, 6, 1) AS offs ) select
date_count.date, count(allocation_id) as packs_used from medicine_allocation,
date_count where site_id = 1 and allocation_id is not null and timestamp
between date_count.date and date_count.date + interval '1 days' group by
date_count.date order by date_count.date;

这确实让我对 table 中的日期有一个很好的聚合视图,但由于没有行来自 2016 年 1 月 4 日之前,因此它们不会显示在结果中:

"2016-01-04 00:00:00";1
"2016-01-05 00:00:00";2
"2016-01-06 00:00:00";4
"2016-01-07 00:00:00";3

我想要这个:

"2016-01-01 00:00:00";0
"2016-01-02 00:00:00";0
"2016-01-03 00:00:00";0
"2016-01-04 00:00:00";1
"2016-01-05 00:00:00";2
"2016-01-06 00:00:00";4
"2016-01-07 00:00:00";3

我也尝试过在 cte 上进行右连接,但这会产生相同的结果。我不太明白该怎么做...有什么帮助吗?

最好的, 剑锋

你只需要 left join:

with date_count as (
      select '2016-01-01'::date + CAST(offs || ' days' as
interval) as date
      from generate_series(0, 6, 1) AS offs
     )
select dc.date, count(ma.allocation_id) as packs_used
from date_count dc left join
     medicine_allocation ma
     on ma.site_id = 1 and ma.allocation_id is not null and
        ma.timestamp between dc.date and dc.date + interval '1 days'
group by dc.date
order by dc.date;

忠告:永远不要FROM子句中使用逗号。 始终 使用显式 JOIN 语法。

您还会注意到 where 条件已移至 ON 子句。这是必要的,因为它们在第二个 table.