CREATE OR REPLACE VIEW v_public_vehiclepositions_past_stop_times AS
SELECT
    sub.trips_id AS rt_trip_id,
    sub.last_stop_sequence AS stop_sequence,
    sub.stop_arr_delay,
    sub.stop_dep_delay,
    sub.last_stop_id AS stop_id
FROM (
    SELECT
        rt_position.trips_id,
        rt_position.last_stop_id,
        rt_position.last_stop_sequence,
        rt_position.delay_stop_arrival,
        rt_position.delay_stop_departure,
        max(rt_position.delay_stop_arrival) AS stop_arr_delay,
        min(rt_position.delay_stop_departure) AS stop_dep_delay
    FROM
        vehiclepositions_positions rt_position
    WHERE (rt_position.delay_stop_arrival IS NOT NULL
        OR rt_position.delay_stop_departure IS NOT NULL)
    AND (rt_position.state_position::text = ANY (ARRAY['on_track'::character varying::text, 'at_stop'::character varying::text, 'after_track'::character varying::text]))
GROUP BY
    rt_position.trips_id,
    rt_position.last_stop_id,
    rt_position.last_stop_sequence,
    rt_position.delay_stop_arrival,
    rt_position.delay_stop_departure) sub
ORDER BY
    sub.trips_id,
    sub.last_stop_sequence;

