Answer the question
In order to leave comments, you need to log in
How to select overlapping intervals?
There is a base consisting of two fields in_time
and out_time
(datetime type).
You need to select pairs of records that have overlapping time intervals. Those. get a table for example:
common_in_time, common_out_time
Ideally the interval is as general as possible (i.e. if multiple records have overlapping intervals, then they are all merged and common_in_time is assigned the earliest in_time date and common_out_time is the latest out_time date)
I do with SQLAlchemy for Flask, but in general the idea is important
Answer the question
In order to leave comments, you need to log in
Add a flag field to the current table to mark viewed intervals.
You create the second table where the summed intervals will be written.
Then something like this:
Select the first unmarked record from the table, use its borders as in and out.
Find the min_in and max_out of all records that intersect with the current one.
If min_in != in or max_out != out, then in := min_in, out := max_out and repeat the previous step.
Record the resulting interval in the results table.
You mark all records in the source table that intersect with the received one.
You repeat the algorithm.
I will answer myself:
t2 = aliased(t1)
a = db.session.query(t1.in_time, t2.out_time).join(t2,
and_(t1.in_time < t2.in_time, t1.out_time > t2.in_time)).all()
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question