I have the following sample data
begin_date end_date
-------------------------------------------
2014-08-27 07:10:00 2014-08-27 07:30:00
2014-08-27 07:30:00 2014-08-27 07:50:00
2014-08-27 07:40:00 2014-08-27 08:00:00
2014-08-27 07:50:00 2014-08-27 08:10:00
2014-08-27 08:10:00 2014-08-27 08:30:00
2014-08-27 08:30:00 2014-08-27 08:50:00
2014-08-27 08:30:00 2014-08-27 08:50:00
I want to identify overlapping time periods.
The expected output is
2014-08-27 07:30:00 2014-08-27 07:50:00
2014-08-27 07:40:00 2014-08-27 08:00:00
2014-08-27 07:50:00 2014-08-27 08:10:00
2014-08-27 08:30:00 2014-08-27 08:50:00
2014-08-27 08:30:00 2014-08-27 08:50:00
(2014-08-27 08:30:00 2014-08-27 08:50:00 overlap with another pair of same data itself)
Please help me out..
Two time periods A and B overlap iff (begin(A) < end(B)) && (end(A) >= begin(B))
. Does that help?
Maybe try something like this:
select p1.begin_date, p1.end_date, ' overlaps ', p2.begin_date, p2.end_date
from periodTable p1
inner join periodTable p2
on p1.begin_date < p2.end_date
and p1.end_date >= p2.begin_date
Edit:
In response to Tanner's comment, I suggest an elaborated version of the above:
select p1.begin_date, p1.end_date
from periodTable p1
inner join periodTable p2
on p1.begin_date < p2.end_date
and p1.end_date > p2.begin_date
group by p1.begin_date, p1.end_date
having count(*) > 1
This will yield all overlapping periods , but not the individual records from the table, that is, each period will only be returned once. (This corresponds to the puristic relational algebra view and is a result of the lack of a primary key.)
Try this :
SELECT REsult.DtFrom, REsult.DtTo
FROM
(
SELECT DtFrom, DtTo, CASE WHEN DtFrom <= cast((LAG(DtTo) OVER(ORDER BY DtFrom, DtTo)) as datetime)
THEN 1 ELSE 0 END AS IsOverlapping
FROM
dbo.Dates_Overlap
) AS REsult
WHERE IsOverlapping = 1
ORDER BY DtFrom, DtTo;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.