Create list with first and last day of month for given period

独自空忆成欢 提交于 2019-12-02 00:37:27

问题


I have to generate a list with two columns of day intervals for every month in a specific period. First column must be the first day of month and the second column the last day of month.

Example:
Start date: 2014-01-01
End date: 2014-06-30

The result should be in two columns:

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

I have two functions that get the first and last day from a date. I am trying to combine two series but with no luck.

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

The second function does not show the last day correctly when it is in the series.


回答1:


Based on this answer:

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



回答2:


You can even use a single interval expression:

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

Details for interval input in the manual.



来源:https://stackoverflow.com/questions/21583877/create-list-with-first-and-last-day-of-month-for-given-period

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