4

我必须为特定时期的每个月生成一个包含两列天间隔的列表。第一列必须是一个月的第一天,第二列必须是一个月的最后一天。

示例:
开始日期:2014-01-01
结束日期:2014-06-30

结果应该在两列中:

1. 2014-01-01 | 2014-01-31
2. 2014-02-01 | 2014-02-28
3. 2014-03-01 | 2014-03-31
4. 2014-04-01 | 2014-04-30
5. 2014-05-01 | 2014-05-31
6. 2014-06-01 | 2014-06-30

我有两个函数可以从日期中获取第一天和最后一天。我正在尝试结合两个系列,但没有运气。

select i::date
from generate_series(first_day('2014-01-01')
                    ,first_day('2014-06-30'), '1 month'::interval) i

select i::date
from generate_series(last_day('2014-01-01')
                    ,last_day('2014-06-30'), '1 month'::interval) i

第二个函数在系列中时不能正确显示最后一天。

4

2 回答 2

5

基于这个答案

select d::date as start_date,(d + '1 month'::interval - '1 day'::interval )::date end_date
from generate_series('2014-01-01'::date, '2014-06-30'::date, '1 month'::interval) d
于 2014-02-05T17:32:33.383 回答
1

加一个月减一天 - 在单个区间表达式中:

SELECT d AS mon_first
     , d + interval '1 month - 1 day' AS mon_last
FROM   generate_series(timestamp '2014-01-01'
                     , timestamp '2014-06-30'
                     , interval  '1 month') d;

进一步阅读(“一天结束”与“一个月的最后一天”非常相似):

关于生成时间序列:

于 2014-02-05T17:37:33.497 回答