Skip to content
Advertisement

Get length of time while status remains the same

I have a history table which looks like this:

The history table is only ever updated when a change occurs, so I can say that the row returned by MAX(DateChanged) is the current state.

Let’s say that ID relates to a shop.

I want to be able to identify the length of time that a currently open shop has been open for.

So I would get an output like this:

ID = 2 would return null because it is currently closed.

I have tried using LAG to get the previous record:

lag(status) over (partition by id order by datechanged)

But I can’t work out how to recursively increase the step until it finds “closed” rather than “open” and return that date.

How could I achieve this?

Advertisement

Answer

If there are only two statuses, you can use conditional aggregation to get the duration.

To get the earliest open date, you can use window functions:

The subquery gets the latest closed date time. This is then used to get the first open date after that.

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