我有以下 postgresql 表;
ID Date
1 [2017-01-01,2051-01-01)
2 [2017-01-01,2051-01-01)
3 [2017-01-01,2051-01-01)
4 [2017-01-01,2051-01-01)
5 [2000-01-01,2017-01-01)
6 [2000-01-01,2017-01-01)
7 [2017-01-01,2051-01-01)
8 [2017-01-01,2051-01-01)
9 [2017-01-01,2051-01-01)
10 [2017-01-01,2051-01-01)
如何在日期范围内进行查询,以便在 2003 年 6 月返回 ID 5 和 6。
最佳答案
使用包含运算符 <@
:
with my_table(id, dates) as (
values
(1, '[2017-01-01,2051-01-01)'::daterange),
(2, '[2017-01-01,2051-01-01)'),
(3, '[2017-01-01,2051-01-01)'),
(4, '[2017-01-01,2051-01-01)'),
(5, '[2000-01-01,2017-01-01)'),
(6, '[2000-01-01,2017-01-01)'),
(7, '[2017-01-01,2051-01-01)'),
(8, '[2017-01-01,2051-01-01)'),
(9, '[2017-01-01,2051-01-01)'),
(10, '[2017-01-01,2051-01-01)')
)
select *
from my_table
where '2003-06-01'::date <@ dates;
id | dates
----+-------------------------
5 | [2000-01-01,2017-01-01)
6 | [2000-01-01,2017-01-01)
(2 rows)
了解 Range Functions and Operators.
您还可以检查 dates:
是否包含日期范围(不是单个日期)
where daterange('2003-01-01', '2003-12-31') <@ dates;
或者日期范围是否重叠 dates:
where daterange('2003-01-01', '2003-12-31') && dates;
关于sql - 查询日期范围postgresql,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48423501/