'How to detect an event and ensure its the first (earliest event that occurred?

I am attempting to extract data from a large patient database using SQL. I need to detect when an event occurred. In this case, it will be a decrease in SpO2 by 10% from when treatment started. It needs to be the earliest time point when it decreased. Example 100%-95-92-97-88-92-89 only the 88 is what I will need. The tricky part begins as patients might have two treatments throughout care. I need to compare these treatments to observe which treatment is the best. An example of the data is below. The patient will have treatment A until treatment B starts or until the final reading and vis versa. the SpO2 values with ** are the ones I need to extract

Date Time SpO2 Treatment
05/19/22 18:23 100 N/A
05/19/22 18:24 95 A
05/19/22 18:25 90 N/A
05/19/22 18:26 85 N/A
05/19/22 18:27 N/A B
05/19/22 18:27 90 N/A
05/19/22 18:28 85 N/A
05/19/22 18:29 80 N/A
05/19/22 18:30 78 N/A
05/19/22 18:31 76 N/A

What I'm hoping the final table looks like is

Date Time SpO2 Treatment
05/19/22 18:23 100 N/A
05/19/22 18:24 95 A
05/19/22 18:26 85 N/A
05/19/22 18:27 N/A B
05/19/22 18:27 90 N/A
05/19/22 18:29 80 N/A

If you can please help, that would be amazing and thank you very much.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source