Let's say I have a table with two columns: start
and end
, both integers, and the table is ordered by the first, then second column. Each row represents an interval.
What I need is the table of merged intervals: all overlapping or adjacent intervals gobbled up into one.
It can be constructed with a JOIN query, but that is quadratic in the number of rows, which is 4 million rows in my case (I decided to compose this question because the query is still running).
It can also be done in a single pass, by running through each row and keeping track of the maximum end time - but how to do that, or something equivalent, in standard SQL? Is there any O(n) way to do it in SQL? I'm using SQLite right now; a SQLite-specific solution would also help me out this time.
From the answers to related questions (1, 2, 3, 4, 5, 6, 7, 8, 9) I can't tell whether it's possible.
Can you?