-- combined view
drop view v_public_vehiclepositions_combined_stop_times;

create view v_public_vehiclepositions_combined_stop_times as
select distinct on (rt_trip_id, stop_sequence)
    stop_times.rt_trip_id,
	vt.gtfs_trip_id,
	stop_times.stop_sequence,
	stop_times.stop_arr_delay,
	stop_times.stop_dep_delay
from (
	select
		*
	from
		v_public_vehiclepositions_future_stop_times prediction
	union all
	select
		*
	from
		v_public_vehiclepositions_past_stop_times history
) as stop_times
join vehiclepositions_trips vt on vt.id = stop_times.rt_trip_id
join vehiclepositions_positions vp on vt.last_position_id = vp.id and (vp.valid_to is null or vp.valid_to >= now()) and vp.state_position != 'after_track'
order by
	rt_trip_id,
    stop_sequence;
