【问题标题】:How to find whether a table has a given date range如何查找表格是否具有给定的日期范围
【发布时间】: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


【解决方案1】:

两个区间相交条件是每个区间必须在另一个结束之前开始:

..
WHERE mt.DISPLAY_START_DATE <= @enddate AND @startdate <= mt.DISPLAY_END_DATE

【讨论】:

    【解决方案2】:

    如果您想选择所有日期都在给定范围内的行,您可以尝试以下查询:

    DECLARE @startdate AS datetime ='2022-02-01' 
    DECLARE @enddate AS datetime ='2022-02-10'
    
    SELECT * from MYTABLE mt
    WHERE 
    (mt.DISPLAY_START_DATE between @startdate and @enddate and mt.DISPLAY_END_DATE between @startdate and @enddate) 
    

    或者,如果您想要一个 where 条件来选择表中完全或部分在范围内的所有行

    SELECT * from MYTABLE mt
    WHERE 
    (mt.DISPLAY_START_DATE between @startdate and @enddate and mt.DISPLAY_END_DATE between @startdate and @enddate) or
    (mt.DISPLAY_START_DATE <=@startdate and mt.DISPLAY_END_DATE >=@enddate) or
    (mt.DISPLAY_START_DATE <=@startdate and mt.DISPLAY_END_DATE between @startdate and @enddate) or
    (mt.DISPLAY_START_DATE between @startdate and @enddate  and mt.DISPLAY_END_DATE >=@enddate) 
    

    【讨论】:

    • 谢谢卡子。我已经使用了您的第二种解决方案。效果很好!
    • 不客气。最良好的祝愿。
    猜你喜欢
    • 2010-11-20
    • 2010-11-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-07
    相关资源
    最近更新 更多