Можете да използвате прозоречни функции lead()
и lag()
за проверка на първия и последния запис, например:
select
max(a.id) as id,
max(a.first) as first,
max(a.last) as last
from (
select
v.id,
case when lag(v.id) over(order by v.id, p.install_date) is null then p.install_date end as first,
case when lead(v.id) over(order by v.id, p.install_date) is null then p.remove_date end as last
from vehicle v
left join period p on (v.id = p.car_id)
where v.id = 1
) as a