查询日期范围PostgreSQL

3
我有以下的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。
2个回答

2
使用包含运算符<@
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)    

阅读范围函数和运算符。


您还可以检查一个日期范围(而不是单个日期)是否包含在dates中:

where daterange('2003-01-01', '2003-12-31') <@ dates;

或者一个日期范围是否与日期重叠:

where daterange('2003-01-01', '2003-12-31') && dates;

如果我们只修改查询为2003年而不包括月份,那么查询会如何改变? - shahzad ise

0

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接