Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Postgresql generate_series of months

I'm trying to generate a series in PostgreSQL with the generate_series function. I need a series of months starting from Jan 2008 until current month + 12 (a year out). I'm using and restricted to PostgreSQL 8.3.14 (so I don't have the timestamp series options in 8.4).

I know how to get a series of days like:

select generate_series(0,365) + date '2008-01-01'

But I am not sure how to do months.

like image 923
Pyrite Avatar asked Sep 16 '11 21:09

Pyrite


2 Answers

select DATE '2008-01-01' + (interval '1' month * generate_series(0,11))

Edit

If you need to calculate the number dynamically, the following could help:

select DATE '2008-01-01' + (interval '1' month * generate_series(0,month_count::int))
from (
   select extract(year from diff) * 12 + extract(month from diff) + 12 as month_count
   from (
     select age(current_timestamp, TIMESTAMP '2008-01-01 00:00:00') as diff 
   ) td
) t

This calculates the number of months since 2008-01-01 and then adds 12 on top of it.

But I agree with Scott: you should put this into a set returning function, so that you can do something like select * from calc_months(DATE '2008-01-01')

like image 167
a_horse_with_no_name Avatar answered Oct 11 '22 20:10

a_horse_with_no_name


You can interval generate_series like this:

SELECT date '2014-02-01' + interval '1' month * s.a AS date
  FROM generate_series(0,3,1) AS s(a);

Which would result in:

        date         
---------------------
 2014-02-01 00:00:00
 2014-03-01 00:00:00
 2014-04-01 00:00:00
 2014-05-01 00:00:00
(4 rows)

You can also join in other tables this way:

SELECT date '2014-02-01' + interval '1' month * s.a AS date, t.date, t.id
  FROM generate_series(0,3,1) AS s(a)
LEFT JOIN <other table> t ON t.date=date '2014-02-01' + interval '1' month * s.a;
like image 42
patrick Avatar answered Oct 11 '22 20:10

patrick