Postgresql generate_series of months

只谈情不闲聊 提交于 2019-11-28 20:41:19
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')

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;

Well, if you only need months, you could do:

select extract(month from days)
from(
  select generate_series(0,365) + date'2008-01-01' as days
)dates
group by 1
order by 1;

and just parse that into a date string...

But since you know you'll end up with months 1,2,..,12, why not just go with select generate_series(1,12);?

You can interval generate_series like this:

SELECT TO_CHAR(months, 'YYYY-MM') AS "dateMonth"
FROM generate_series(
    '2008-01-01' :: DATE,
    '2008-06-01' :: DATE ,
    '1 month'
) AS months

Which would result in:

 dateMonth 
-----------
 2008-01
 2008-02
 2008-03
 2008-04
 2008-05
 2008-06
(6 rows)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!