I have a table that looks as follows:
| TS | Serial Number | Activity | Address |
|---|---|---|---|
| 1 | 123456 | AAAABBBBCCCC | |
| 2 | 123456 | AAAABBBBCCCC | |
| 3 | 123456 | A | AAAABBBBCCCC |
| 4 | 123456 | E | AAAABBBBCCCC |
| 5 | 876543 | A | UNIUNIUNIUNI |
| 6 | 123456 | A | AAAABBBBCCCC |
| 7 | 123456 | E | WAHWAHWAHWAH |
| 8 | 123456 | WAHWAHWAHWAH | |
| 9 | 876543 | E | ALFALFALFALF |
| 10 | 876543 | ALFALFALFALF |
TS is a timestamp column that usually contains an ISO date string. I've shortened this for simplicity.
As you can see, a change in the Address field CAN occur whenever there's an Activity = E.
The ungrouped rows can be in semi-arbitrary order, though each Activity A within a group, when sorted by timestamp (TS), MUST always be followed by an Activity E, however not necessarily immediately. There CAN be <null> Activities in between the A and E. If there is no E following the last A within a group, sorted by TS, the corresponding Serial Number can safely be considered invalid.
For each Serial Number, sorted by TS in ascending order, I need the Address of the last occurrence of Activity = E, if and only if that last E is NOT followed by another A, otherwise Address may contain INVALID or alternatively the corresponding Serial Number can be omitted from the result.