通过单个查询返回日期在指定范围内的列表
我正在尝试获取范围内的日期列表,类似于PostgreSQL中的命令NOW(),唯一的区别是 now()
仅返回当前日期。
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;
结果为昨天
2013-09-27 15:27:50.303-05
什么我需要一个可以返回给定范围内每个日期的列表的查询,因此,如果我提供2013-09-20和2013-09-27(我对小时数也不感兴趣,只提供日期),我想获得如下输出:
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 ...
使用 generate_series()
,完全符合您的需求
Use generate_series()
, does exactly what you need:
SELECT generate_series('2013-09-20'::date
, '2013-09-27'::date
, interval '1 day')::date;
采用两个 timestamp
变量,但日期
也被接受。
返回带有时区的时间戳$ c>,所以我强制转换为
date
根据您的要求。
Takes two timestamp
variables, but dates
are also accepted.
Returns timestamp with time zone
, so I cast to date
according to your request.
更详细,但在语法上更清晰的版本是使用set returning function(SRF)as FROM
项目:
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;
请考虑以下注释。