R
R
Roman Mindlin2017-05-14 18:56:29
Flask
Roman Mindlin, 2017-05-14 18:56:29

How to select overlapping intervals?

There is a base consisting of two fields in_timeand 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

2 answer(s)
R
Rsa97, 2017-05-15
@Rsa97

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.

R
Roman Mindlin, 2017-05-15
@kgbplus

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()

t2 is needed because SQLAlchemy doesn't allow join with itself.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question