CREATE OR REPLACE VIEW v_vehiclepositions_past_stop_times
AS SELECT sub.trips_id AS rt_trip_id,
    sub.last_stop_sequence AS stop_sequence,
    sub.last_stop_id AS stop_id,
    sub.last_stop_arrival_time AS stop_arrival,
    sub.last_stop_departure_time AS stop_departure,
    min(sub.delay_stop_arrival) AS stop_arr_delay,
    max(sub.delay_stop_departure) AS stop_dep_delay
   FROM ( SELECT rt_position.trips_id,
            rt_position.last_stop_sequence,
            rt_position.last_stop_id,
            rt_position.last_stop_arrival_time,
            rt_position.last_stop_departure_time,
            rt_position.delay_stop_arrival,
            rt_position.delay_stop_departure,
            row_number() OVER seq AS rn
           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]))
          WINDOW seq AS (PARTITION BY rt_position.trips_id, rt_position.last_stop_sequence, rt_position.state_position ORDER BY rt_position.id)) sub
  WHERE sub.rn = 1
  GROUP BY sub.trips_id, sub.last_stop_arrival_time, sub.last_stop_departure_time, sub.last_stop_sequence, sub.last_stop_id
  ORDER BY sub.trips_id, sub.last_stop_sequence;


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,
    min(sub.delay_stop_arrival) AS stop_arr_delay,
    max(sub.delay_stop_departure) AS 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,
            row_number() OVER seq AS rn
           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, 'at_stop'::character varying, 'after_track'::character varying]::text[]))
          WINDOW seq AS (PARTITION BY rt_position.trips_id, rt_position.last_stop_sequence, rt_position.state_position ORDER BY rt_position.id)) sub
  WHERE sub.rn = 1
  GROUP BY sub.trips_id, sub.last_stop_sequence, sub.last_stop_id
  ORDER BY sub.trips_id, sub.last_stop_sequence;