首页 > 解决方案 > 从数据库中选择记录,日期为“As-On”,已过日期?

问题描述

我在数据库中有一个带有 start_date、end_date 的表,我想使用日期过滤器从数据库中获取记录,以获取这些记录"As on given date"。例如:

Id   start_date    end_date
1    1980-01-01    1984-12-31
2    1985-01-01    2009-12-31
3    2010-01-01    2018-12-31
4    2019-01-01    null
5    1940-01-01    null

所以现在如果我传递日期(期望的输出

**1940-01-01**, it should return #Id=5 (number of records == 1)
**1980-01-02**, it should return #Id=1,5 (number of records == 2)
**1985-01-01**, it should return #Id=1,2,5 (number of records == 3)
**2010-01-01**, it should return #Id=1,2,3,5 (number of records == 4)
**2019-01-01**, it should return #Id=1,2,3,4,5 (number of records == 5)
**2021-01-01**, it should return #Id=1,2,3,4,5 (number of records == 5)

我尝试了许多查询,但似乎没有一个像

select * from table where (end_date <= '1980-01-02' or end_date is null)

select * from table where '1980-01-01 00:00:00' between start_date and coalesce(end_date, '2999-12-31')

select * from table where (end_date <= '1980-01-01 00:00:00' or end_date is null) and start_date <= '1980-01-01 00:00:00' 

任何帮助都会得到帮助。

标签: sqlpostgresqldatedate-range

解决方案


对我来说有意义的逻辑是:

select t.*
from t
where :date >= start_date and
      (:date <= end_date or end_date is null);

但是,这与您陈述的结果不一致。它符合我对您想要的内容的阅读。


推荐阅读