This is a type of gaps-and-islands problem. You can identify the groups by counting the number of non-50+ rows up to each row. Then, aggregate the groups with the conditions you want:
select grp, sum(value)
from (select t.*,
sum(value < 50) over (order by timestamp) as grp
from t
) t
where value >= 50
group by grp
having count(*) >= 2;
This produces a separate value for each adjacent values. If you want the total sum, then you can use a subquery or CTE based on this query.
If you actually just want the overall sum, you can use lead()
and lag()
:
select sum(value)
from (select t.*,
lag(value) over (order by timestamp) as prev_value,
lead(value) over (order by timestamp) as next_value
from t
) t
where value >= 50 and
(prev_value >= 50 or next_value >= 50)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…