Skip to content
Advertisement

MySQL select based on earlier row’s data (audit table)

I have an audit table that is structured as follows:

This table is tracking whether we were able to successfully source a particular data point for a customer.

Sometimes we are able to find the data on the first attempt, and you know this because there was no entry with a status of failed, the first occurrence of a particular field was tagged successful (e.g. phone)

Other times, we fail to find the data point on the first n searches but eventually are able to find it. You know this because are one or more entries with a status of failed, then later a status of successful (e.g. website).

I am having trouble writing a MySQL query that would only select the fields where we previously failed to find the data point but then were able to find it.

Ideally, this query would produce an output of:

I couldn’t see any similar questions, although it’s tricky to describe what I am looking for. Any help would be appreciated!

Advertisement

Answer

For MySql 8.0+ you can do it with LAG() window function:

For previous versions of MySql, assuming that the column id is increasing for any new attempt:

See the demo.
Results:

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