简体   繁体   English

如何在Postgresql中生成从开始日期到now()之间的月份

[英]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() . 但是现在我希望它从2018年6月1日到now() What's the best way to do this. 最好的方法是什么。

Oh, postgresql 10. yay!! 哦,PostgreSQL 10。

Your query gives a list of first and last days of months between "2018-06-01" and now. 您的查询提供了从“ 2018-06-01”到现在的月份的第一天和最后几天的列表。 So I am assuming that you want to this in a more dynamic way: 因此,我假设您想以更动态的方式做到这一点:


demo: db<>fiddle 演示: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. generate_series(timestamp, timestamp, interval)生成一个时间戳列表。 Starting with "2018-06-01" until now() with the 1 month interval gives this: 从“ 2018-06-01”开始直到now() ,间隔为1个月,结果如下:

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. 这些时间戳通过::date cast转换为日期。

Then I add 1 month to get the next month. 然后我添加1个月以获得下个月。 But as we are interested in the last day of the previous month I subtract one day again ( + interval '1 month -1 day' ) 但是,由于我们对上个月的最后一天感兴趣,因此我又减去了一天( + interval '1 month -1 day'

Another option that's more ANSI-compliant is to use a recursive CTE: 更加符合ANSI的另一个选项是使用递归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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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