Skip to content
Advertisement

Get next row with clause A since last row with clause B

I have the following table:

I am looking for a way to get all customers whose status is currently not ‘ok’ with an indication since when the status is not ‘ok’. The result should be:

My attempt is the following, but it gives incorrect values for customers that are currently ‘ok’.

The thing that I try to figure out is getting the first row for each customer with a not-‘ok’ status, since the last ‘ok’-status. How can I achieve this in Postgres?

Advertisement

Answer

You can assign a grouping to the rows based on the count of 'ok' statuses on or after each row.

Then, just filter where the count is 0 and aggregate:

Here is a db<>fiddle.

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