2016-03-11 23 views
0

在我的表中,我有一些条目 - 在表格的日期列 - 不会比2016-01-04(2016年1月4日)更旧。 现在我想进行一个查询,它或多或少地计算具有特定日期值的行数,但我希望此查询能够返回表中不存在日期的0计数。包含来自cte的值,当它不匹配

我有这样的:

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右连接,但这种收益率相同的结果。我不能完全掌握如何做到这一点...有什么帮助吗?

最佳, 剑锋

回答

1

你只需要一个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条款。这是必要的,因为他们在第二张桌子上。

+0

优秀!!非常感谢。我自己非常亲密(用我的右连接),但是你的帮助使我免于很多挫折:)我可以问为什么不使用逗号,但只加入语法? –

+0

@JanusEngstrøm。 。 。 'JOIN'语法更强大。没有理由使用逗号(可以使用'CROSS JOIN'来代替)。大多数人发现逻辑更容易跟随'JOIN'。 –