问题描述
我正在尝试使用generate_series函数在PostgreSQL中生成一个系列。我需要从2008年1月开始的几个月,直到本月+ 12
(一年)。我正在使用PostgreSQL 8.3.14(仅限于8.4)(因此我没有8.4中的时间戳系列选项)。
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'
但我不确定该怎么做。
推荐答案
select DATE '2008-01-01' + (interval '1' month * generate_series(0,11))
编辑
如果需要动态计算数字,请执行以下操作可以帮助:
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
此计算自2008年1月以来的月数-01,然后在其顶部加上12。
This calculates the number of months since 2008-01-01 and then adds 12 on top of it.
但是我同意Scott的观点:您应该将其放入返回的集合函数中,以便可以执行 select * from calc_months(DATE'2008-01-01')
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')
这篇关于PostgreSQL generate_series月的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!