有什么办法可以使我的查询也返回空行?

时间:2019-06-17 12:42:44

标签: sql postgresql group-by

我有一个查询来获取计划的数量,每十分钟进行分组(请参阅下文),但是当某十分钟内的计划数量为0时,查询什么也不返回,我该如何返回甚至如果其为0。 返回示例:

10  2019-06-01 00:00:00
5   2019-06-01 00:10:00
5   2019-06-01 00:30:00
8   2019-06-01 00:40:00

我想返回这样的内容:

10  2019-06-01 00:00:00
5   2019-06-01 00:10:00
0   2019-06-01 00:20:00
5   2019-06-01 00:30:00
8   2019-06-01 00:40:00

在这里查询:

select count(distinct(s.tracking_uid)) as "Scheduled",
to_timestamp(floor((extract('epoch' from s.created_date) / 600 )) * 600) 
AT TIME ZONE 'UTC' as TenMin
from table.example se 
inner join table.example2 s on s.tracking_uid = se.tracking_uid
where
date(s.created_date) >= '2019/06/01'
and date(s.created_date) < '2019/06/17'
group by TenMin

1 个答案:

答案 0 :(得分:0)

使用generate_series()生成所需的值:

with e as (
      select e.*,
             to_timestamp(floor((extract('epoch' from s.created_date) / 600 )) * 600) at timezone 'UTC' as tz
      from example e
      where s.created_date >= '2019-06-01'::timestamp and
            s.created_date < '2019-06-18'::timestamp
     ) 
select gs.min10, count(distinct e.tracking_id)
from (select generate_series(min(tz), max(tz), interval '10 minute' as min10
      from e
     ) gs left join
     example e
     on e.ts = gs.min10
group by gs.min10
order by gs.min10;