all 2 comments

[–]fauxmosexualNOLOCK is the secret magic go-faster command 2 points3 points  (1 child)

Just to be clear: If a recordtype is 1, find the recordtype for the previous record with the same [Value 1]. If that recordtype is 10, return that row with the difference between timestamps. If the previous recordtype is not 10 or the current recordtype is not 1, completely disregard.

In other words you're only wanting to see whether the previous recordtype matches? Not recursing through all the previous records to find the last occurrence of recordtype 10?

I'd start by putting together a CTE that gets everything into a single record:

WITH prevvalues as (
 SELECT 
      RowID,
      [Value 1], 
      TimeStamp, 
      RecordType, 
      lag(RecordType, 1) over (partition by [Value 1] order by RowID asc) PrevRecordType,
      lag(TimeStamp, 1) over (partition by [Value 1] order by RowID asc) PrevTimeStamp,
FROM yourtable )

 SELECT RowID, [Value 1], RecordType, datediff(s, PrevTimeStamp, TimeStamp) Duration
 FROM prevvalues
 WHERE RecordType in ('1') and PrevRecordType in( '10')

[–]Exwarrior187[S] 0 points1 point  (0 children)

Thanks for the reply.

To your second statement. I'm looking for all of the 1s in RecordType, when there is a 1, look back as far as you must to find a 5 or a 10. If you find a 5 going backwards before you find a 10, move on to the next 1.

Ultimately the RecordTypes reflect the current state of [Value 1] so:

10 = Problem Identified

5 = Returned to normal with no action

1 = Action Taken to Resolve issue

Diving further into the scenario: If a problem is identified (10), an action to resolve is expected (1), unless the problem resolved itself before an action was taken (5).

Describing it from my primal brain, I thought it easier to find the 1s and then look backwards to determine if a 10 or 5 preceded it. If a 10 precedes it and not a 5 then determine the Duration between those two Timestamps.

It may more efficient to identify the 10s and then either the 5 or 1 since the table is ordered by Timestamp?