从数据库中选择记录,日期为“截止日期”,已过日期?

时间:2020-08-14 20:12:28

标签: sql postgresql date date-range

我在数据库中有一个表,其开始日期为start_date,结束日期为end_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' 

将提供任何帮助。

2 个答案:

答案 0 :(得分:0)

为此使用<a href="example.com/app" id="1">1</a> <a href="https://example.com/app" id="2">2</a> <a href="example.com/app" id="3">3</a> <a href="" id="4">4</a> <a id="5">5</a> <a href="https://example.com/app" class="6">6</a> <a href="https://example.com/app">7</a> infinity文字和timestamp

between

答案 1 :(得分:0)

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

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

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

相关问题