Transformations > Expression transformation > Example: Use a window to flag GPS pings
  

Example: Use a window to flag GPS pings

Your organization receives GPS pings from vehicles that include trip and event IDs and a time stamp. You want to calculate the time difference between each ping and flag the row as skipped if the time difference with the previous row is less than 60 seconds.
You order the events chronologically and partition the events by trip. You define a window function that accesses the event time from the previous row, and you use an ADD_TO_DATE function to calculate the time difference between the two events.

Window properties

Property
Value
Description
Frame
Not specified
Window functions access rows based on the offset argument and ignore the frame.
Partition key
trip_id
Groups the rows according to trip ID so that calculations are based on events from the same trip.
Order key
_event_id Ascending
Arranges the data chronologically by ascending event ID.

Window function

You define the following LAG function to get the event time from the previous row:
LAG ( _event_time, 1, NULL )
For more information about the LAG function, see Function Reference.
You define the following DATE_DIFF function to calculate the length of time between the two dates:
DATE_DIFF ( _event_time, LAG ( _event_time, 1, NULL ), 'ss' )
You flag the row as skipped if the DATE_DIFF is less than 60 seconds, or if the _event_time is NULL:
IIF ( DATE_DIFF < 60 or ISNULL ( _event_time ), 'Skip', 'Valid' )

Output

The transformation produces the following outputs:
Trip ID
Event ID
Event Time
Time Difference
Flag
101
1
2017-05-03 12:00:00
NULL*
Skip
101
2
2017-05-03 12:00:34
34
Skip
101
3
2017-05-03 12:02:00
86
Valid
101
4
2017-05-03 12:02:23
23
Skip
102
1
2017-05-03 12:00:00
NULL*
Skip
102
2
2017-05-03 12:01:56
116
Valid
102
3
2017-05-03 12:02:00
4
Skip
102
4
2017-05-03 13:00:00
3480
Valid
103
1
2017-05-03 12:00:00
NULL*
Skip
103
2
2017-05-03 12:00:12
12
Skip
103
3
2017-05-03 12:01:12
60
Valid
*The rows preceding these rows are outside the bounds of the partition, so the LAG function produces NULL values.