Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
199 views
in Technique[技术] by (71.8m points)

sql - Finding MySQL records that have at least 2 consective timestamp or ID records

I need to run a report that finds the sum of records that have a value in a certain field ( >50 ), but only when there are at least 2 consecutive timestamps. Once the timestamps stop being consecutive, i then need to ignore the until we find the next 2 consecutive.

1  2021-01-26 09:45:58     50
2  2021-01-26 09:47:23     20
3  2021-01-26 09:47:29     50
4  2021-01-26 09:48:23     50

in the example above, The first record would (ID1) would fail (only 1 hit in the required timescale ) ID2 (value too low ) but records 3 and 4 would qualify for inclusion in the sum.

question from:https://stackoverflow.com/questions/65917754/finding-mysql-records-that-have-at-least-2-consective-timestamp-or-id-records

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...