Skip to content

Instantly share code, notes, and snippets.

@kleong
Created February 11, 2020 22:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kleong/3e8bdf8c90cbd0cab1b4df7138596218 to your computer and use it in GitHub Desktop.
Save kleong/3e8bdf8c90cbd0cab1b4df7138596218 to your computer and use it in GitHub Desktop.
/* Grouping events emitted in last 5 seconds by vehicleId and getting the time of the oldest event in this group */
WITH vehicles_in_last_5_seconds AS (
SELECT
vehicleinfo.vehicleId,
vehicleinfo._event_time,
vehicleinfo.latitude,
vehicleinfo.longitude
from
commons.vehicleinfo
WHERE
vehicleinfo._event_time > CURRENT_TIMESTAMP() - SECONDS(5)
),
older_sample_time_for_vehicles as (
SELECT
MIN(vehicles_in_last_5_seconds._event_time) as min_time,
vehicles_in_last_5_seconds.vehicleId
FROM
vehicles_in_last_5_seconds
GROUP BY
vehicles_in_last_5_seconds.vehicleId
),
older_sample_location_for_vehicles AS (
SELECT
vehicles_in_last_5_seconds.latitude,
vehicles_in_last_5_seconds.longitude,
vehicles_in_last_5_seconds.vehicleId
FROM
older_sample_time_for_vehicles,
vehicles_in_last_5_seconds
where
vehicles_in_last_5_seconds._event_time = older_sample_time_for_vehicles.min_time
and vehicles_in_last_5_seconds.vehicleId = older_sample_time_for_vehicles.vehicleId
),
latest_sample_time_for_vehicles as (
SELECT
MAX(vehicles_in_last_5_seconds._event_time) as max_time,
vehicles_in_last_5_seconds.vehicleId
FROM
vehicles_in_last_5_seconds
GROUP BY
vehicles_in_last_5_seconds.vehicleId
),
latest_sample_location_for_vehicles AS (
SELECT
vehicles_in_last_5_seconds.latitude,
vehicles_in_last_5_seconds.longitude,
vehicles_in_last_5_seconds.vehicleId
FROM
latest_sample_time_for_vehicles,
vehicles_in_last_5_seconds
where
vehicles_in_last_5_seconds._event_time = latest_sample_time_for_vehicles.max_time
and vehicles_in_last_5_seconds.vehicleId = latest_sample_time_for_vehicles.vehicleId
),
distance_for_vehicles AS (
SELECT
ST_DISTANCE(
ST_GEOGPOINT(
CAST(older_sample_location_for_vehicles.longitude AS float),
CAST(older_sample_location_for_vehicles.latitude AS float)
),
ST_GEOGPOINT(
CAST(latest_sample_location_for_vehicles.longitude AS float),
CAST(latest_sample_location_for_vehicles.latitude AS float)
)
) as distance,
latest_sample_location_for_vehicles.vehicleId
FROM
latest_sample_location_for_vehicles,
older_sample_location_for_vehicles
WHERE
latest_sample_location_for_vehicles.vehicleId = older_sample_location_for_vehicles.vehicleId
)
SELECT
*
from
distance_for_vehicles
ORDER BY
distance_for_vehicles.distance DESC
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment