create
or replace 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,
    vt.gtfs_route_type,
    vt.gtfs_route_short_name,
    vt.run_number,
    vt.internal_run_number,
    vt.provider_source_type,
    vt.cis_trip_number,
    vt.vehicle_registration_number,
    stop_times.stop_id,
    vcs.cis_stop_platform_code,
    rs.platform_code
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'
    left join ropidgtfs_stops rs on rs.stop_id = stop_times.stop_id
    left join ropidgtfs_cis_stops rcs on rcs.id = rs.computed_cis_stop_id
    left join vehiclepositions_cis_stops vcs
        on vcs.rt_trip_id = stop_times.rt_trip_id
        and vcs.cis_stop_group_id = rcs.cis
order by
    rt_trip_id,
    stop_sequence;
