【发布时间】:2022-02-08 12:52:16
【问题描述】:
我想查明一个表是否有在传递给查询的日期范围内的行。以下是MYTABLE中的数据。我正在使用 SQL Server
DISPLAY_START_DATE DISPLAY_END_DATE
2022-02-02 00:00:00.000 2022-02-28 00:00:00.000
2022-02-02 00:00:00.000 2022-02-06 10:34:01.653
2022-02-01 00:00:00.000 2022-02-17 00:00:00.000
2022-02-07 00:00:00.000 2022-02-25 00:00:00.000
以下是我的查询
DECLARE @startdate AS datetime ='2022-02-01'
DECLARE @enddate AS datetime ='2022-02-10'
SELECT * from MYTABLE mt
WHERE
(mt.DISPLAY_START_DATE = @startdate and mt.DISPLAY_END_DATE = @enddate) OR
(mt.DISPLAY_START_DATE < @startdate and mt.DISPLAY_END_DATE > @enddate) OR
(mt.DISPLAY_START_DATE < @startdate and mt.DISPLAY_END_DATE < @enddate) OR
(mt.DISPLAY_START_DATE < @startdate and mt.DISPLAY_END_DATE < @enddate and
mt.DISPLAY_END_DATE > @startdate) OR
(mt.DISPLAY_START_DATE > @startdate and mt.DISPLAY_END_DATE < @enddate) OR
(mt.DISPLAY_START_DATE > @startdate and mt.DISPLAY_START_DATE < @enddate and
mt.DISPLAY_END_DATE < @enddate)
这只会拉出与以下数据对应的第二行
DISPLAY_START_DATE DISPLAY_END_DATE
2022-02-02 00:00:00.000 2022-02-06 10:34:01.653
【问题讨论】:
-
请提及您想要的输出以便更好地理解。
-
精确定义“范围内的含义”。我建议您绘制一条实际时间线,将表格中任何给定日期时间范围的开始点和结束点添加为示例,然后在时间线上方绘制开始和结束参数的范围以直观地看到 他们如何比较。您可能正在寻找“完全包含在其中”、“在其中结束但可以随时开始”等。Serg 的建议可能会满足您的需求 - 但要求非常不确定。
标签: sql sql-server date-comparison