1

在查看日期范围时,是否还有generate_series返回开始日期和结束日期?

select 
    '2014-06-05 00:00:00'::timestamp + ('1 month'::INTERVAL * s.a) AS date 
from 
    generate_series(1, cast(extract(month from age('2014-09-05'::date, '2014-06-05'::date)) AS integer), 1) as s(a);

给出这个输出

date
2014-07-05 00:00:00
2014-08-05 00:00:00
2014-09-05 00:00:00

这很好,但是我想拥有

start_date     end_date       date
2014-06-05    2014-09-05    2014-07-05 00:00:00
2014-06-05    2014-09-05    2014-08-05 00:00:00
2014-06-05    2014-09-05    2014-09-05 00:00:00

原因是我正在从另一个表中提取多个开始/结束对,但无法找出将它们连接在一起的方法。我也在使用 PostgeSQL 版本 8.2.15(因此generate_series功能更复杂)。

为了将此扩展到我的主要问题,我有一个包含这些开始和结束时间对的表。

    start_date         end_date
2014-08-25 00:00:00 2014-09-25 00:00:00
2014-05-16 00:00:00 2014-08-16 00:00:00
2014-09-09 00:00:00 2014-12-09 00:00:00
2014-06-05 00:00:00 2014-07-05 00:00:00
2014-05-19 00:00:00 2014-08-19 00:00:00
2014-05-15 00:00:00 2014-07-15 00:00:00
2014-09-04 00:00:00 2014-11-04 00:00:00

如何遍历此表并将其与扩展的日期范围连接?

4

1 回答 1

2

考虑升级到当前版本。Postgres 8.2 早已死去并被遗忘。

对于 Postgres 8.2(或更高版本,但现代 Postgres 中有更优雅的解决方案)。

假设这都是关于日期,而不是时间戳。

提供一次start_date_end_date

SELECT start_date, end_date
     , (start_date + interval '1 month'
                   * generate_series(1, months))::date AS the_date
FROM  (  
   SELECT extract(month from age(end_date, start_date))::int AS months
        , start_date, end_date
   FROM (SELECT '2014-06-05'::date AS start_date
              , '2014-09-05'::date AS end_date
        ) data
   ) sub;

使用列名the_date而不是date不应用作标识符。

而是从表中绘制值t

SELECT start_date, end_date
     ,(start_date + interval '1 month'
                  * generate_series(1, months))::date AS the_date
FROM  (SELECT *, extract(month FROM age(end_date, start_date))::int AS months
       FROM   t) sub;

没有子查询

SELECT t_id, start_date, end_date
     ,(start_date + interval '1 month'
                  * generate_series(1, extract(month from age(end_date
                                                            , start_date))::int)
                  )::date AS the_date
FROM   t;

Postgres 8.3 的SQL 小提琴

于 2014-09-19T20:19:24.310 回答