我正在尝试使用 generate_series 函数在 PostgreSQL 中生成一个系列。我需要从 2008 年 1 月到current month + 12
(一年后)的一系列月份。我正在使用并仅限于 PostgreSQL 8.3.14(所以我在 8.4 中没有时间戳系列选项)。
我知道如何获得一系列的日子,例如:
select generate_series(0,365) + date '2008-01-01'
但我不确定如何做几个月。
我正在尝试使用 generate_series 函数在 PostgreSQL 中生成一个系列。我需要从 2008 年 1 月到current month + 12
(一年后)的一系列月份。我正在使用并仅限于 PostgreSQL 8.3.14(所以我在 8.4 中没有时间戳系列选项)。
我知道如何获得一系列的日子,例如:
select generate_series(0,365) + date '2008-01-01'
但我不确定如何做几个月。
select DATE '2008-01-01' + (interval '1' month * generate_series(0,11))
编辑
如果您需要动态计算数字,以下可能会有所帮助:
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-01-01 以来的月数,然后在其上加上 12。
但我同意斯科特的观点:你应该把它放到一个集合返回函数中,这样你就可以做类似的事情select * from calc_months(DATE '2008-01-01')
您可以像这样间隔 generate_series:
SELECT date '2014-02-01' + interval '1' month * s.a AS date
FROM generate_series(0,3,1) AS s(a);
这将导致:
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)
您也可以通过这种方式加入其他表:
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;
你可以这样间隔generate_series
:
SELECT TO_CHAR(months, 'YYYY-MM') AS "dateMonth"
FROM generate_series(
'2008-01-01' :: DATE,
'2008-06-01' :: DATE ,
'1 month'
) AS months
这将导致:
dateMonth
-----------
2008-01
2008-02
2008-03
2008-04
2008-05
2008-06
(6 rows)
好吧,如果你只需要几个月,你可以这样做:
select extract(month from days)
from(
select generate_series(0,365) + date'2008-01-01' as days
)dates
group by 1
order by 1;
并将其解析为日期字符串...
但是既然你知道你最终会得到 1,2,..,12 个月,为什么不直接选择select generate_series(1,12);
呢?
您可以在generated_series()
其中定义步骤,在您的情况下为一个月。因此,您可以动态定义开始日期(即 2008-01-01)、结束日期(即 2008-01-01 + 12 个月)和步骤(即 1 个月)。
SELECT generate_series('2008-01-01', '2008-01-01'::date + interval '12 month', '1 month')::date AS generated_dates
你得到
1/1/2008
2/1/2008
3/1/2008
4/1/2008
5/1/2008
6/1/2008
7/1/2008
8/1/2008
9/1/2008
10/1/2008
11/1/2008
12/1/2008
1/1/2009