Selecting the last record that meets a condition
Prior answer was wrong as pointed out in the comments -- this works:

SELECT id, val, 
       CASE when val &lt; 5 then (
            select max(val) from t as tsub where tsub.id &lt; t.id) 
       else val end as newval
FROM T


have to use a sub query to find the prior max.