sql - 从数据库中选择记录,日期为“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'
任何帮助都会得到帮助。
解决方案
对我来说有意义的逻辑是:
select t.*
from t
where :date >= start_date and
(:date <= end_date or end_date is null);
但是,这与您陈述的结果不一致。它符合我对您想要的内容的阅读。
推荐阅读
- python - 在 pyaudio 部分中使用 Speech_recognition 时出错
- javascript - 在 Angular 属性和事件调用参数中使用 tag 'value 属性
- aws-lambda - 如何以编程方式将 CloudWatch 事件添加到 lambda 函数?
- c# - 两个窗体在屏幕中具有相同的位置但不同的位置
- scala - 如何在 Scala 中使用 foreach 和 concat 重现 flatMap?
- c# - LLBLGEN:从一个表查询并插入另一个表
- android - 使用Object animator android向左滑动
- docker - SQLAlchemy + pymssql - 无法从 jupyter 内核网关 docker 连接到 sql db
- discord.py - discord.py 宣布命令
- c - pragma gcc 优化功能