Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have sample data like

Element Time Stamp
A 21/12/2020 06:10:56
B 21/12/2020 06:05:27
B 21/12/2020 06:06:10
A 21/12/2020 06:11:27
A 21/12/2020 06:05:27
A 21/12/2020 06:06:20
A 21/12/2020 06:12:30

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
2.4k views
Welcome To Ask or Share your Answers For Others

1 Answer

If I understand correctly, you want "islands" that are separated by 90 seconds. If so, you can use lag() and a cumulative sum with aggregation:

select element, min(timestamp), max(timestamp), count(*)
from (select t.*,
             sum(case when prev_timestamp > dateadd(second, -90, timestamp) then 0 else 1 end) over (partition by element order by timestamp) as grp
      from (select t.*,
                   lag(timestamp) over (partition by element order by timestamp) as prev_timestamp
            from t
           ) t
     ) t
group by grp, element;

Here is a db<>fiddle.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...