Return list with dates within a specified range from a single query

有些话、适合烂在心里 提交于 2019-12-11 21:25:06

问题


I'm trying to obtain a list of dates within range, similar to the command NOW() in PostgreSQL, with the only difference that now(), returns only the current date.

If I execute it as follows I obtain:

select now();

2013-09-27 15:27:50.303-05

Or by example, I could do this:

select now() - interval '1' day;

and the result is yesterday

2013-09-27 15:27:50.303-05

What I need is a query that could return a list with every date within a given range, so if I provide 2013-09-20 and 2013-09-27 (I'm nor really interested in hours, only dates) I would like to obtain an output as follows:

2013-09-20
2013-09-21
2013-09-22
2013-09-23
2013-09-24
2013-09-25
2013-09-26
2013-09-27

Any ideas on how to achieve this? By preference without using stored procedures or functions, unless there is no other way ...


回答1:


Use generate_series(), does exactly what you need:

SELECT generate_series('2013-09-20'::date
                     , '2013-09-27'::date
                     , interval '1 day')::date;

Takes two timestamp variables, but dates are also accepted.
Returns timestamp with time zone, so I cast to date according to your request.

A more verbose, but syntactically clearer version is to use the set returning function (SRF) as FROM item:

SELECT *
FROM   generate_series('2013-09-20'::date
                     , '2013-09-27'::date
                     , interval '1 day')::date;

Consider the comments below.



来源:https://stackoverflow.com/questions/19059654/return-list-with-dates-within-a-specified-range-from-a-single-query

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