给定一组日期范围的PostgreSQL查询

给定一组日期范围的PostgreSQL查询,postgresql,Postgresql,假设我们有上述数据。如何构造查询,以便在给定日期的情况下获取当前有效项 例如。因为今天是2017年11月29日,所以我应该得到C项 我已经试过了,但我只是想知道是否有更有效的查询 Table name: sample --Item--|---datefrom---|--dateto-- Item A |0001-01-01 |2099-01-01 Item B |2017-11-20 |2017-12-31 Item C |2017-11-27

假设我们有上述数据。如何构造查询,以便在给定日期的情况下获取当前有效项

例如。因为今天是2017年11月29日,所以我应该得到C项

我已经试过了,但我只是想知道是否有更有效的查询

Table name: sample
   --Item--|---datefrom---|--dateto-- 
   Item A  |0001-01-01    |2099-01-01
   Item B  |2017-11-20    |2017-12-31
   Item C  |2017-11-27    |2017-12-12

以下查询将返回范围与当前日期重叠的最新项目:

select * from sample where datefrom>= (select datefrom from sample where datefrom < '2017-11-29' order by datefrom desc limit 1 ) and dateto <= (select dateto from sample where dateto > '2017-11-29' order by dateto limit 1)
如果两个或两个以上的项目恰好是最新的,并且您想要所有的联系,那么只需将row_number替换为rank即可

但据我所知,你的A项有一个范围,可能也包括今天。我不知道为什么它的范围从零年开始,或者这是否有效/有意义

正如@a_horse所指出的,如果我们确定/不关心项目之间的关系是否最接近,我们可以使用以下简化查询:

select *
from
(
    select *,
        row_number() over (order by abs(current_date - datefrom)) rn
    from sample
    where current_date between datefrom and dateto
) t
where rn = 1;

为什么不直接从示例中选择*其中datefrom=now按datefrom限制1排序?有效项。项C应优先。顺便说一句,您的查询不返回任何行。不相关,但是:在Postgres中,您可以使用-infinity和infinity来代替这些神奇的日期。如果没有返回行,它将作为默认值。如果有两个或更多匹配项,将如何确定报告哪个项,听起来总是这样?它应该返回最接近当前日期的行。例如,在A项和C项之间。C项应优先,因为它是最接近的。哪个日期定义了最接近的日期?截止日期还是起始日期?您不需要窗口功能。您只需在原始查询版本中使用order by ABCURRENT_date-DATEFORM limit 1即可。
select *
from sample
where current_date between datefrom and dateto
order by abs(current_date - datefrom)
limit 1;