Hi,
I have a table where I have datetimes associated with an ID:
┌────────────────┬──────────────────────┐
│ location_id | datetime |
├────────────────┼──────────────────────┤
│ 200333 | 2008-01-01 00:00:00 |
│ 200333 | 2008-01-01 01:00:00 |
│ 200333 | 2008-01-01 02:00:00 |
| ... | ... |
│ 200333 | 2009-10-23 21:00:00 |
│ 200333 | 2009-10-23 22:00:00 |
│ 200333 | 2008-10-23 23:00:00 |
│ 200768 | 2008-06-01 00:00:00 |
│ 200768 | 2008-06-01 01:00:00 |
│ 200768 | 2008-06-01 02:00:00 |
| ... | ... |
│ 200768 | 2009-12-31 00:00:00 |
│ 200768 | 2009-12-31 00:00:00 |
│ 200768 | 2009-12-31 00:00:00 |
└────────────────┴──────────────────────┘
What would be the way to select the longest time period these two overlapping location_id
's share? In this case, the desired output would be:
┌──────────────────────┬──────────────────────┐
│ start | end |
├──────────────────────┼──────────────────────┤
│ 2008-06-01 00:00:00 | 2009-10-23 23:00:00 |
└──────────────────────┴──────────────────────┘
I can easily get the longest period available using MIN()
and MAX()
but how would I go about selecting the maximum of minimum datetimes and minimum of maximum datetimes?
Oh, and this table contains 19 000 000 rows, so bonus points for suggestions that run fast :)