在 PostgreSQL 中生成两个日期之间的时间序列 [英] Generating time series between two dates in PostgreSQL

查看:38
本文介绍了在 PostgreSQL 中生成两个日期之间的时间序列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个这样的查询,它很好地生成了 2 个给定日期之间的一系列日期:

I have a query like this that nicely generates a series of dates between 2 given dates:

select date '2004-03-07' + j - i as AllDate 
from generate_series(0, extract(doy from date '2004-03-07')::int - 1) as i,
     generate_series(0, extract(doy from date '2004-08-16')::int - 1) as j

它在 2004-03-072004-08-16 之间生成 162 个日期,这是我想要的.此代码的问题在于,当两个日期来自不同年份时,例如当我尝试 2007-02-012008-04-01 时,它不会给出正确答案.

It generates 162 dates between 2004-03-07 and 2004-08-16 and this what I want. The problem with this code is that it wouldn't give the right answer when the two dates are from different years, for example when I try 2007-02-01 and 2008-04-01.

有更好的解决方案吗?

推荐答案

无需转换到/从 int 即可完成(但要/从时间戳改为)

Can be done without conversion to/from int (but to/from timestamp instead)

SELECT date_trunc('day', dd):: date
FROM generate_series
        ( '2007-02-01'::timestamp 
        , '2008-04-01'::timestamp
        , '1 day'::interval) dd
        ;

这篇关于在 PostgreSQL 中生成两个日期之间的时间序列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆