sql select first and last record of each group
select v.*
from (select v.*,
row_number() over (partition by vehicleid, tripid order by datetime asc) as seqnum_asc,
row_number() over (partition by vehicleid, tripid order by datetime desc) as seqnum_desc
from vehicles v
) v
where seqnum_asc = 1 or seqnum_desc = 1;