1select v.*
2from (select v.*,
3 row_number() over (partition by vehicleid, tripid order by datetime asc) as seqnum_asc,
4 row_number() over (partition by vehicleid, tripid order by datetime desc) as seqnum_desc
5 from vehicles v
6 ) v
7where seqnum_asc = 1 or seqnum_desc = 1;