Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/postgresql/9.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
缺少值的Postgresql完成日期(ts,';小时';)_Postgresql_Datetime - Fatal编程技术网

缺少值的Postgresql完成日期(ts,';小时';)

缺少值的Postgresql完成日期(ts,';小时';),postgresql,datetime,Postgresql,Datetime,我有一个带有ts值的表,一个int表示一个事件在该ts中发生的次数。 问题在于,如果ts中没有事件,则该ts不会记录在DB中,如以下示例所示: ts | n ------------------------- 2014-09-26 01:00:00| 10 2014-09-26 03:00:00| 12 2014-09-26 05:00:00| 1 2014-09-26 06:00:00| 2 2014-09-26 07:00:00| 4 2014-0

我有一个带有ts值的表,一个int表示一个事件在该ts中发生的次数。 问题在于,如果ts中没有事件,则该ts不会记录在DB中,如以下示例所示:

ts                 |  n
-------------------------
2014-09-26 01:00:00|  10
2014-09-26 03:00:00|  12
2014-09-26 05:00:00|  1
2014-09-26 06:00:00|  2
2014-09-26 07:00:00|  4
2014-09-26 08:00:00|  3
我需要做的是执行一个查询,该查询可以在间隔内完成所有缺失的ts值(trun at hour),以获得如下结果:

ts                 |  n
-------------------------
2014-09-26 01:00:00|  10
2014-09-26 02:00:00|  0
2014-09-26 03:00:00|  12
2014-09-26 04:00:00|  0
2014-09-26 05:00:00|  1
2014-09-26 06:00:00|  2
2014-09-26 07:00:00|  4
2014-09-26 08:00:00|  3

谢谢你的帮助

您需要生成ts的最小值和最大值之间所有可能值的列表,然后根据表外部连接:

with min_max as (
    select min(date_trunc('hour', ts)) as min_hour,
           max(date_trunc('hour', ts)) as max_hour
    from the_table
)
select s.s, coalesce(t.n, 0)
from generate_series( (select min_hour from min_max), (select max_hour from min_max), interval '1' hour) as s
   left join the_table t on s.s = date_trunc('hour', t.ts)
order by s.s;
如果这不需要是动态的,并且您可以硬编码开始和结束日期,这看起来更容易理解:

select s.s, coalesce(t.n, 0)
from generate_series( timestamp '2014-09-26 01:00:00', timestamp '2014-09-26 08:00:00', interval '1' hour) as s
   left join the_table t on s.s = date_trunc('hour', t.ts)
order by s.s;

这是唯一的办法吗??我的表有50个工厂记录,此查询最多需要2.3分钟。。。有没有更快的办法??