Postgres-在date_trunc中没有数据的间隔返回0计数

时间:2018-07-10 21:20:55

标签: sql postgresql

我正在尝试创建一个表格,列出我在10天内每5分钟间隔多少计数。我认为我的联接是错误的,因为我没有在查询中得到空行。

select date_trunc('minute', activities.activitytime) - 
    (CAST(EXTRACT(MINUTE FROM activities.activitytime)    
    AS integer) % 5) * interval '1 minute' as day_column, count(activities.activityid)

from generate_series(current_date - interval '10 day', current_date, '1 minute') d 

left join activities on date(activities.activitytime) = d 

group by day_column 
order by day_column;

enter image description here

1 个答案:

答案 0 :(得分:1)

您很近。但是关键思想是您需要将generate_series()的列用于group by键:

select d.dte, count(a.activitytime)
from generate_series(current_date - interval '10 day', current_date, '5 minute') d(dte) left join
     activities a
     on a.activitytime >= d.dte and a.activitytime < d.dte + interval '5 minute'
group by d.dte 
order by d.dte;