【问题标题】:Checking if a given date fits between a range of dates检查给定日期是否适合日期范围
【发布时间】:2012-10-31 15:09:47
【问题描述】:

如果我在一个表中有 2 个日期列,startDateendDate。如何返回给定日期介于这两个日期之间的行?例如:

如果给定日期是2012-10-25

它应该返回以下行

startDate   -   endDate
2012-10-25  -   2012-10-25
2011-09-10  -   2013-11-15
2012-10-20  -   2012-10-25
2012-10-23  -   2012-10-28
2012-09-14  -   2012-10-28

从以下行:

startDate   -   endDate
2012-10-25  -   2012-10-25
2011-09-10  -   2013-11-15
2012-01-11  -   2012-10-11
2012-10-20  -   2012-10-25
2012-04-15  -   2012-04-16
2012-05-20  -   2012-05-25
2012-12-01  -   2012-12-10
2012-10-23  -   2012-10-28
2012-09-14  -   2012-10-28
2012-11-13  -   2012-12-15

用 sql 可以吗?

我使用的是 sql server 2008。

【问题讨论】:

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


    【解决方案1】:

    使用 SQL Server 实际上很简单:

    SELECT startDate, endDate
    FROM YourTable
    WHERE '2012-10-25' between startDate and endDate
    

    【讨论】:

    • 如果我有两个日期发现两个日期之间的日期在这个开始日期之间是否可用。
    • 像开始日期是 1 结束日期是 10 如果我有两个日期 3 作为开始和 6 作为结束。所以我能找到 3 和 6 在 1 和 10 之间吗?
    • 如何在查询中添加两个日期,如 ('2012-10-25', '2012-10-26')?
    • 有没有办法只检查它是否在一个没有结束日期的日期之后?
    【解决方案2】:

    检查BETWEEN关键字。

    语法很简单:

    SELECT col1, col2
    FROM table1
    WHERE '2012-10-25' BETWEEN col1 and col2
    

    其中 col1 和 col2 分别是开始日期和结束日期。

    【讨论】:

      【解决方案3】:

      对于其他研磨检查,以下可能会很有趣

      Select * from sted where [dbo].[F_LappingDays](Startdate,EndDate,'20121025','20121025')=1
      
      
      CREATE Function [dbo].[F_LappingDays](@Von1 datetime,@bis1 Datetime,@von2 Datetime,@bis2 Datetime) Returns int as
      /*
      20110531 Thomas Wassermann
      Terminüberschneidungen finden
      */
      begin
      Declare @Result int
      
      Select @Result  = 0
      if (@Von1>=@Von2) and (@bis1<=@Bis2)
          begin
              Select @Result=Cast(@Bis1 - @von1 + 1 as Int)
          end
      
      else if (@Von1<=@Von2) and (@bis1 > @Von2) and (@bis1<=@Bis2)
          begin
              Select @Result=Cast(@Bis1 - @von2 + 1 as Int)
          end
      
      else if (@Von1>=@Von2) and (@von1<=@bis2) and (@bis1>@Bis2)
          begin
              Select @Result=Cast(@Bis2 - @von1 + 1 as Int)
          end
      
      else if (@Von1<@Von2) and (@bis1>@Bis2)
          begin
              Select @Result=Cast(@Bis2 - @von2 + 1 as Int)
          end
      
      
      
      Return @Result
      end 
      

      【讨论】:

        【解决方案4】:

        您可以使用 between 运算符来查找两个约束之间的值。这对于查找某个范围内的日期也很有用。

        SELECT startDate, endDate FROM sampleTable WHERE '2012-10-25' between startDate and endDate 
        

        了解更多BETWEEN

        【讨论】:

          猜你喜欢
          • 2020-04-07
          • 1970-01-01
          • 1970-01-01
          • 2017-01-28
          • 1970-01-01
          • 1970-01-01
          • 2010-11-01
          • 2010-11-20
          • 1970-01-01
          相关资源
          最近更新 更多