Created
January 18, 2022 18:19
-
-
Save Mr--John-Doe/99e9284a1d5603fc63fe8c0cbdb322f6 to your computer and use it in GitHub Desktop.
for every accident, show how much time (in hours) has passed since the last time the road became Wet/Damp.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
WITH relevant_set AS ( | |
SELECT * | |
-- has_started_raining means: (previous!=Wet AND current=Wet) | |
, LAG(road_cond) OVER (ORDER BY accident_ts, police_ref) AS prev_road_cond | |
, prev_road_cond != '2. Wet/Damp' AND road_cond = '2. Wet/Damp' AS has_started_raining | |
, CASE WHEN has_started_raining THEN accident_ts END AS time_started_raining | |
FROM temp.CAMBRIDGESHIRE_ACCIDENTS | |
) | |
SELECT accident_ts | |
, police_ref | |
, LAST_VALUE(time_started_raining) | |
IGNORE NULLS | |
OVER (ORDER BY accident_ts ROWS UNBOUNDED PRECEDING) AS last_it_started_raining_ts | |
, DATEDIFF(HOUR, last_it_started_raining_ts, accident_ts) AS elapsed_since_last_rained_hh | |
FROM relevant_set | |
ORDER BY 1, 2 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment