在我的表中,我有一些条目--表中的日期列--不早于2016-01-04 (2016年1月4日)。现在,我想要进行一个查询,它或多或少地计算具有特定日期值的行数,但是我希望这个查询能够返回表中不存在的日期的0计数。
我有这个:
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;这无疑给了我对表中日期的一个很好的汇总视图,但是由于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上尝试了右联接,但这也产生了同样的结果。我不知道该怎么做.有什么帮助吗?
最好的,贾纳斯
发布于 2016-03-11 01:30:14
你只需要一个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子句中。这是必要的,因为它们在第二张桌子上。
https://stackoverflow.com/questions/35930572
复制相似问题