简体   繁体   中英

How do I generate months between start date and now() in postgresql

I also have the question how do i get code block to work on stack overflow but that's a side issue.

I have this quasi-code that works:

select
    * 
from 
    unnest('{2018-6-1,2018-7-1,2018-8-1,2018-9-1}'::date[],
           '{2018-6-30,2018-7-31,2018-8-31,2018-9-30}'::date[] 
    ) zdate(start_date, end_date)
left join lateral pipe_f(zdate...

But now I want it to work from 6/1/2018 until now() . What's the best way to do this.

Oh, postgresql 10. yay!!

Your query gives a list of first and last days of months between "2018-06-01" and now. So I am assuming that you want to this in a more dynamic way:


demo: db<>fiddle

SELECT
    start_date,
    (start_date + interval '1 month -1 day')::date as end_date
FROM (
    SELECT generate_series('2018-6-1', now(), interval '1 month')::date as start_date
)s 

Result :

start_date  end_date
2018-06-01  2018-06-30
2018-07-01  2018-07-31
2018-08-01  2018-08-31
2018-09-01  2018-09-30
2018-10-01  2018-10-31

generate_series(timestamp, timestamp, interval) generates a list of timestamps. Starting with "2018-06-01" until now() with the 1 month interval gives this:

start_date
2018-06-01 00:00:00+01
2018-07-01 00:00:00+01
2018-08-01 00:00:00+01
2018-09-01 00:00:00+01
2018-10-01 00:00:00+01

These timestamps are converted into dates with ::date cast.

Then I add 1 month to get the next month. But as we are interested in the last day of the previous month I subtract one day again ( + interval '1 month -1 day' )

Another option that's more ANSI-compliant is to use a recursive CTE:

WITH RECURSIVE
    dates(d) AS
    (
        SELECT '2018-06-01'::TIMESTAMP
        UNION ALL
        SELECT d + INTERVAL '1 month'
        FROM dates 
        WHERE d + INTERVAL '1 month' <= '2018-10-01'
    )
SELECT 
    d AS start_date, 
    -- add 1 month, then subtract 1 day, to get end of current month
    (d + interval '1 month') - interval '1 day' AS end_date
FROM dates

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM