查询日期范围postgresql

query date ranges postgresql

我有以下 postgresql table;

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 月 returns ID 5 和 6。

https://www.postgresql.org/docs/current/static/functions-range.html

使用包含运算符,例如:

postgres=# select '[2000-01-01,2017-01-01)'::daterange @> '2013.01.01'::date;
 ?column?
----------
 t
(1 row)

所以对你来说就像

select * from tbl where "Date" @> '2013.01.01'::date;

使用包含运算符<@:

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;