Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
474 views
in Technique[技术] by (71.8m points)

sql - 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
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')


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...