简体   繁体   English

在PostgreSQL查询中使用generate_series

[英]Using generate_series in PostgreSQL query

I have a table with data and I want to fill the date gaps with generate_series with PostgreSQL but I can't solve it. 我有一个数据表,我想用PostgreSQL填充generate_series的日期空白,但我无法解决它。 How can I join my table to the generate_series result? 如何将我的表连接到generate_series结果? My attempt is the following: 我的尝试如下:

SELECT series AS time,
       data 
FROM generate_series('2012-11-11', '2012-11-12', '2 minutes'::interval) AS series
LEFT JOIN data_table ON data_table.time = series

In this date range the result is: 在此日期范围内,结果为:

               TIME             DATA
        2012.11.11. 13:00:06 | data 1
        2012.11.11. 13:08:06 | data 2 

My aim would be similar like this: 我的目标是这样的:

            TIME            DATA
    2012.11.11. 13:00:06 | data 1
    2012.11.11. 13:02:06 | NULL
    2012.11.11. 13:06:06 | NULL
    2012.11.11. 13:08:06 | data 2 
    2012.11.11. 13:10:06 | NULL
    2012.11.11. 13:12:06 | NULL
    ...

Ergo the the whole table fill with time rows with 2 minutes interval. 因此,整个表填充时间行,间隔为2分钟。 How can I achieve this? 我怎样才能做到这一点?

I think your query should work. 我认为您的查询应该有效。 I would give the value a column name: 我会给值一个列名:

SELECT g.series AS time, t.data 
FROM generate_series('2012-11-11', '2012-11-12', '2 minutes'::interval) AS g(series) LEFT JOIN
      data_table t
      ON t.time = g.series;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM