【问题标题】:Check if date is overlapping in SQL检查 SQL 中的日期是否重叠
【发布时间】:2015-04-24 17:58:09
【问题描述】:

我有一个表 tblBranchTimingEntry

+---------------+-------------------------+-------------------------+------------------+
| BranchEntryID |        fromDate         |         toDate          |     SundayIn     |
+---------------+-------------------------+-------------------------+------------------+
|            24 | 2015-01-01 00:00:00.000 | 2015-01-31 00:00:00.000 | 12:00:00.0000000 |
|            24 | 2015-02-01 00:00:00.000 | 2015-02-15 00:00:00.000 | 12:00:00.0000000 |
|            24 | 2015-03-01 00:00:00.000 | 2015-03-31 00:00:00.000 | 00:00:00.0000000 |
|            24 | 2014-01-01 00:00:00.000 | 2014-12-31 00:00:00.000 | 00:00:00.0000000 |
+---------------+-------------------------+-------------------------+------------------+

要求

我正在输入 BranchEntryID、fromDate、toDate,我想检查 fromDate 和 toDate 之间的任何日期是否与 tblBranchTimingEntry 中存储的日期范围重叠。


到目前为止我做了什么

我有这个问题

SELECT 
        * 
    FROM
        [dbo].[tblBranchTimingEntry] 

    WHERE
        BranchEntryId = 24
    AND
        ('2015-01-14' BETWEEN fromDate AND toDate OR '2015-02-28' BETWEEN fromDate AND toDate)

这将检查重叠。


问题

仅当输入日期介于数据库中的日期之间时才有效。 在本例中这将失败。

假设我将 fromdate 和 todate 设为“2015-02-16”和“2015-08-27”, 此查询不会返回任何内容。但是这些日期之间有重叠的日期。

任何解决方案?

【问题讨论】:

标签: sql sql-server sql-server-2008


【解决方案1】:

试试这个逻辑:

SELECT te.* 
FROM [dbo].[tblBranchTimingEntry]  te
WHERE BranchEntryId = 24 AND
      '2015-01-14' < toDate AND
      '2015-02-28' > fromDate;

取决于您所说的“重叠”,可能是&lt;= 和/或&gt;=

逻辑是:两个日期范围重叠是第一个开始在第二个结束之前,第一个在第二个开始之后结束。

【讨论】:

    【解决方案2】:

    试试这个:

    SELECT 
            * 
    FROM
            [dbo].[tblBranchTimingEntry]
    WHERE
        BranchEntryId = 24
    AND
        (('2015-01-14' < toDate AND
      '2015-01-14' > fromDate) or ('2015-02-28' > fromDate and '2015-02-28' < toDate) or ('2015-02-28' > toDate AND
      '2015-01-14' < fromDate))
    

    这样您就可以检查是否有任何日期在 fromDate 和 ToDate 之间

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-11-04
      • 1970-01-01
      • 2013-09-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多