Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

determine if date range falls between another date range - sql

Tags:

sql

datetime

tsql

I am trying to find out if there is a way in sql (t-sql preferred) to identify if a date range falls between another date range.

for purposes of my example: daterange1 = i have a defined date range, dates are 1/1/2012 - 1/5/2012 daterange2 = i have two other dates to work with, lets say 1/3/2012 and 1/4/2012

i am trying to have this to use in a CASE statement for something like this

CASE 
    WHEN daterange1 = 0 then result1
    WHEN daterange2 falls within daterange1 then result2 
    END as datestuff 

is this possible in SQL? I'm really stumped on this one, i know how to figure out if a single date falls between a range, but how can it be done with a date range? the answer doesnt necessarily need to be in a CASE statement but it is preferred.

like image 292
wondergoat77 Avatar asked Oct 11 '12 23:10

wondergoat77


People also ask

How do you check if a date lies between two dates in SQL?

You can use the between operator to find the values between two constraints. This also useful to find the dates which is in a range.

How does SQL determine overlapping dates?

You can do this by swapping the ranges if necessary up front. Then, you can detect overlap if the second range start is: less than or equal to the first range end (if ranges are inclusive, containing both the start and end times); or. less than (if ranges are inclusive of start and exclusive of end).

How do I select records between two dates in SQL?

SELECT * FROM ATM WHERE TRANSACTION_TIME BETWEEN '2005-02-28 21:00:00' AND '2008-12-25 00:00:00';


1 Answers

How can you get daterange1 = 0, since it's a range, i.e. 2 values?

The proper test for overlapping dates is

CASE WHEN @range1start <= @range2end
      and @range2start <= @range1end THEN 1 ELSE 0 END

If you mean that daterange2 must fall ENTIRELY within daterange1, then

CASE WHEN @range1start <= @range2start
      and @range2end <= @range1end THEN 1 ELSE 0 END
like image 115
RichardTheKiwi Avatar answered Oct 22 '22 23:10

RichardTheKiwi