Friday 15 January 2021

Select values between start date and end date

I have a table with some events and each event have a start date and end date. For example: Table eventos_sapo

id   titulo imagem startDate endDate
1    ...    ...    2011-02-12   2015-02-12
2    ...    ...    2013-02-21   2015-02-12
3    ...    ...    2014-03-14   2015-02-12

I try some queries to get the events between some start and end dates, introduced by the user through my web app, but none of the queries returns the event with id=1. Let's say that the user introduce the start date=2013-01-03and the end date=2015-02-14, should return the events 1,2 and 3, but the event with id=1 is not returned by none of my queries.

Here goes what I tried:

Select id from eventos_sapo where startDate >= '2013-01-03' AND endDate <= '2015-02-14'

Select id from eventos_sapo where startDate BETWEEN '2013-01-03' AND '2015-02-14'
AND endDate BETWEEN '2013-01-03' AND '2015-02-14'

What I have to do, to include the event with id=1, because this event is active.


ANSWER:

I read this problem as looking for the overlap of ranges:

so you have data in range: T1 to T3. And looking for overlap with range T2 to T4. Since they overlap, you want. However, if data is T1 to T3 and range is T4 to T5 .. no overlap so don't want.

You can do that with this query:

Select id 
  from eventos_sapo 
 where startDate <= '2015-02-14'
   AND endDate >= '2013-01-03';

So if it started after the given date (Feb 14, 2015), then don't include it. or if it ended prior to Jan 3, 2013 ... don't include it. Include everything else, since it overlaps:

As 1 example: Data ends after the given range start date, and the data start date is prior to end, so it's one of the following cases:

Data:           |---|
Given range:      |---|

Data:           |-------|
Given range:      |---|

Data:             |---|
Given range:    |---|

Data:             |---|
Given range:    |-------|

No comments:

Post a Comment