Skip to content

Instantly share code, notes, and snippets.

@kleong
Created February 11, 2020 22:50
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/f424bc09e958d8bb670cbf1055aa5424 to your computer and use it in GitHub Desktop.
Save kleong/f424bc09e958d8bb670cbf1055aa5424 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.speed
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_speed_for_vehicles AS (
SELECT
vehicles_in_last_5_seconds.speed,
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_speed_for_vehicles AS (
SELECT
vehicles_in_last_5_seconds.speed,
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
)
SELECT
latest_sample_speed_for_vehicles.speed,
older_sample_speed_for_vehicles.speed,
older_sample_speed_for_vehicles.vehicleId
from
older_sample_speed_for_vehicles, latest_sample_speed_for_vehicles
WHERE
older_sample_speed_for_vehicles.vehicleId = latest_sample_speed_for_vehicles.vehicleId
AND latest_sample_speed_for_vehicles.speed < older_sample_speed_for_vehicles.speed - 20
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment