I have a query where I am checking for the first instance of a status. The issue is that the status can vary in some circumstances.
For example I have records like the following and the correct record would be ID=12 because it is the first instance the item was actually Covered. 10 appears so, but then it changed to Available again so would not be the final position the record is set to Covered.
ID | PreviousValue | CurrentValue | DateCreated |
---|---|---|---|
10 | Available | Covered | 2024-03-01 |
11 | Covered | Available | 2024-03-02 |
12 | Available | Covered | 2024-03-03 |
13 | Covered | Dispatched | 2024-03-04 |
The other complexity is that in same cases I may have the following where there is no Available instance, it just starts as Covered and I would need to know that, that is the record I am looking for.
ID | PreviousValue | CurrentValue | DateCreated |
---|---|---|---|
10 | Covered | Dispatched | 2024-03-04 |
11 | Dispatched | In-Transit | 2024-03-05 |
I tried something like this, but it does not seem to return the correct record from the first recordset above.
select *
from loads_fieldupdates
where theField = 'loadStatus'
and loadid = 261574
and (
/* most common scenario */
(previousFieldVal LIKE 'Available%' AND theFieldVal LIKE 'Covered%')
OR
/* case where load was duped so started as covered but not went back to available */
(previousFieldVal LIKE 'Covered%' AND theFieldVal NOT LIKE 'Available%')
)
order by dateCreated desc