I am working with time series data that are results of sensor measurements. I need to identify cases where the data flatlines- indicating a sensor malfunction. I want to select where there are more than 3 unchanging values in a row within the last 24 hours.
I think I might need to loop through, but I haven't worked with loops in sql. I assume I'll need to use a subquery to ORDER BY the DateTime. I've also looked at LEAD and LAG. Furthermore, I need to distinguish by SiteID and VariableID, which I think can be done using PARTITION.
Data looks like:
**SiteID**VariableID**DateTime**Value**
5 1 2014-01-27 12:15 5.576
5 1 2014-01-27 12:30 5.487
5 1 2014-01-27 12:45 5.573
5 1 2014-01-27 13:00 5.903
5 87 2014-01-27 12:15 -273.2
5 87 2014-01-27 12:30 -273.2
5 87 2014-01-27 12:45 -273.2
5 87 2014-01-27 13:00 -273.2
5 88 2014-01-27 12:15 -273.2
5 88 2014-01-27 12:30 -273.2
5 88 2014-01-27 12:45 -273.2
5 88 2014-01-27 13:00 -273.2
5 89 2014-01-27 12:15 -273.2
5 89 2014-01-27 12:30 -273.2
5 89 2014-01-27 12:45 -273.2
5 89 2014-01-27 13:00 -273.2
5 2 2014-01-27 12:15 30.61
5 2 2014-01-27 12:30 38.73
5 2 2014-01-27 12:45 32.84
5 2 2014-01-27 13:00 31.62
5 3 2014-01-27 12:15 -9.53
5 3 2014-01-27 12:30 -8.61
5 3 2014-01-27 12:45 -8.76
5 3 2014-01-27 13:00 -9.32
5 4 2014-01-27 12:15 0.298
5 4 2014-01-27 12:30 0.32
5 4 2014-01-27 12:45 0.317
5 4 2014-01-27 13:00 0.302
I want to generate something like:
**SiteID**VariableID**StartingDateTime**ValueCount**Value**
5 87 2014-1-27 12:15 4 -273.4
5 88 2014-1-27 12:15 4 -273.4
5 89 2014-1-27 12:15 4 -273.4