2012-10-31 148 views
14

如果我在表格中有兩個日期列,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

回答

37

有了SQL Server它實際上是簡單的:

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

如果我有兩個日期,發現兩個日期之間的日期是該開始日期之間的可用或不。 –

+0

像開始日期是1結束日期是10如果我有兩個日期3作爲開始和6作爲結束。所以我可以發現3&6在1和10之間。 –

3

檢查BETWEEN關鍵字。

語法很簡單:

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

其他lappingcheck以下可能是有趣

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>[email protected]) and (@bis1<[email protected]) 
    begin 
     Select @Result=Cast(@Bis1 - @von1 + 1 as Int) 
    end 

else if (@Von1<[email protected]) and (@bis1 > @Von2) and (@bis1<[email protected]) 
    begin 
     Select @Result=Cast(@Bis1 - @von2 + 1 as Int) 
    end 

else if (@Von1>[email protected]) and (@von1<[email protected]) 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 
相關問題