I have a table called trips that looks like this:
id | vehicle_id | start_time | end_time |
----+------------+---------------------+---------------------+
1 | 1 | 2014-06-16 22:00:00 | 2014-06-24 03:30:00 |
2 | 1 | 2014-06-24 05:00:00 | 2014-06-28 05:00:00 |
3 | 2 | 2014-06-23 02:00:00 | 2014-06-30 04:00:00 |
...
SQL Fiddle: http://www.sqlfiddle.com/#!12/7c92e/1 (PG 9.2 only because 9.3 was overloaded on SQL Fiddle the time.)
start_time and end_time are both timestamps.
What I'd like to do find trips involving the same vehicle_id where the start_time of a subsequent trip takes place on the same calendar day or the next calendar day of the end_time of a prior trip.
As an example, rows with ID 1 and 2 above would be returned, because:
2'sstart_timetakes place on the same calendar day (2014-06-24) as1; and- both rows have the same
vehicle_id
It's quite possible this isn't sensible to do in SQL. Any advice, tips or pointers to relevant Postgres functions welcome.