bummm26
bummm26

Reputation: 159

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. How can I join my table to the generate_series result? 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. How can I achieve this?

Upvotes: 3

Views: 5006

Answers (1)

Gordon Linoff
Gordon Linoff

Reputation: 1269803

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;

Upvotes: 7

Related Questions