![](/img/trans.png)
[英][postgresql - generate months from start_date and end_date base on total_x]
[英]How do I generate months between start date and now() in postgresql
我也有一個問題,如何使代碼塊在堆棧溢出時起作用,但這是一個附帶問題。
我有這個准代碼可以工作:
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...
但是現在我希望它從2018年6月1日到now()
。 最好的方法是什么。
哦,PostgreSQL 10。
您的查詢提供了從“ 2018-06-01”到現在的月份的第一天和最后幾天的列表。 因此,我假設您想以更動態的方式做到這一點:
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
結果 :
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)
生成一個時間戳列表。 從“ 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
這些時間戳通過::date
cast轉換為日期。
然后我添加1個月以獲得下個月。 但是,由於我們對上個月的最后一天感興趣,因此我又減去了一天( + interval '1 month -1 day'
)
更加符合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.