Skip to content
Advertisement

Finding time range for column value change in SQL

I have a table with eventTime and status as columns as shown below.

I need to produce time range during which status remains the same as shown below.

Appreciate if anyone can help on how to do this in query?

Advertisement

Answer

This is a gap-and-islands problem. In this version, you seem to want the times to “tile” with no gaps. For this version, the simplest method is probably lag() and lead():

This works by taking the first row where the status changes (using the lag()). When the intermediate rows are filtered out, it gets the next start time for the end time.

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement