By using db<>fiddle, you agree to license everything you submit by Creative Commons CC0.
select DateTime
,last_group as Message
from (
select *
,case when Message = 'Test1' and start_end = 1 then null else Message end as last_group
from (
select *
,count(case when Message = 'Test2' then 1 when Message = 'Test4' then 1 end) over(order by DateTime) as start_end
from t
) t
) t
where last_group is not null
DateTime | Message |
---|---|
2022-09-09 00:00:00.000 | Test1 |
2022-09-09 01:00:00.000 | Test2 |
2022-09-09 04:00:00.000 | Test3 |
2022-09-09 05:00:00.000 | Test4 |
2022-09-09 06:00:00.000 | Test1 |
Warning: Null value is eliminated by an aggregate or other SET operation.