2012-10-31 9 views
14

Se ho 2 colonne di data in una tabella, startDate e endDate. Come posso restituire righe in cui una determinata data si inserisce tra queste due date? Per esempio:Verifica se una data specifica si adatta tra un intervallo di date

Se la data indicata è 2012-10-25

Dovrebbe restituire le seguenti righe

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 

dalle righe seguenti:

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 

Questo è possibile con SQL?

sto utilizzando sql server 2008.

risposta

37

Con SQL Server è in realtà il più semplice:

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

Che cosa succede se ho due date per scoprire che la data tra due data è disponibile tra questa data di inizio o non. –

+0

Come la data di inizio è 1 la data di fine è 10 e se ho due date 3 come inizio e 6 come fine. così posso trovare che 3 e 6 sono tra 1 e 10. –

3

Controllare BETWEEN parola chiave.

sintassi è semplice:

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

per altri lappingcheck la seguente potrebbe essere interessante

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 
Problemi correlati