Quantcast
Channel: User Net Dawg - Stack Overflow
Viewing all articles
Browse latest Browse all 32

SQL to Extract Continuous Timestamp Ranges

$
0
0

Table Device_Status

IdStatusTimestamp
1Active2023-01-13T18.00.01.0187528
2Active2023-01-13T18.00.01.0187529
1Failed2023-01-13T18.00.01.0187530
3Active2023-01-13T18.00.01.0187531
1Failed2023-01-13T18.00.01.0187532
1Active2023-01-13T18.00.01.0187533
3Active2023-01-13T18.00.01.0187534
1Failed2023-01-13T18.00.01.0187535
4Failed2023-01-13T18.00.01.0187536
1Active2023-01-13T18.00.01.0187537

Expected Output (Need SQL query to generate):

IDFail_BeginFail_End
12023-01-13T18.00.01.01875302023-01-13T18.00.01.0187532
12023-01-13T18.00.01.01875352023-01-13T18.00.01.0187535
42023-01-13T18.00.01.01875362023-01-13T18.00.01.0187536

Basically, for each ID get min (timestamp) and max (timestamp) but over continuous records for that ID. If there is only one record, then min=max as is the case with the second and third record in the sample result set.

I have tried this (and various subquery variants thereof)

SELECT Id, min(Timestamp) AS Fail_Begin, max(Timestamp) AS Fail_EndFROM Device_StatusGROUP BY Id

but need to group by only continuously occurring records,

So perhaps by adding a notion of status change first would help? Starting with zero as initial status and then incrementing the change code by 1 every time the next record is different in order to thereby generate an intermediate result like so...

Table Device_Status_With_Change_Column

IdStatusChangeTimestamp
1Active02023-01-13T18.00.01.0187528
2Active02023-01-13T18.00.01.0187529
1Failed12023-01-13T18.00.01.0187530
3Active02023-01-13T18.00.01.0187531
1Failed12023-01-13T18.00.01.0187532
1Active22023-01-13T18.00.01.0187533
3Active02023-01-13T18.00.01.0187534
1Failed32023-01-13T18.00.01.0187535
4Failed02023-01-13T18.00.01.0187536
1Active42023-01-13T18.00.01.0187537

And then doing

SELECT Id, Change, min(Timestamp) AS Fail_Begin, max(Timestamp) AS Fail_EndFROM Device_Status_With_Change_ColumnGROUP BY Id, Change

Other than looping over the result set in a programming language, I do not yet see a direct SQL statement that would do this in one fell swoop without the intermediate table and I do not see how to compute the column Change (in SQL).


Viewing all articles
Browse latest Browse all 32

Latest Images

Trending Articles



Latest Images

<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>