Looking at the comments above, I assume that the first scenario of Chris is the one you need (all 3 are grouped, although the values ββ1 and 3 are not within 30 seconds of each other, but in each of them within 30 seconds after the value 2). Also suppose each row in your table has a unique identifier called "id". You can do the following:
- Create a new group to determine whether the previous line in your section is more than 30 seconds behind the current line (for example, determine whether you need a new 30 second grouping or continue the previous one). We will call this parent_id.
- Amount amount by parent_id (plus any other aggregates)
The code may look like this
select sub.parent_id, sub.cusip, min(sub.timestamp) min_timestamp, sum(sub.quantity) quantity from ( select base_sub.*, case when base_sub.self_parent_id is not null then base_sub.self_parent_id else lag(base_sub.self_parent_id) ignore nulls over ( partition by my_table.cusip order by my_table.timestamp, my_table.id ) parent_id from ( select my_table.id, my_table.cusip, my_table.timestamp, my_table.quantity, lag(my_table.timestamp) over ( partition by my_table.cusip order by my_table.timestamp, my_table.id ) previous_timestamp, case when datediff( second, nvl(previous_timestamp, to_date('1900/01/01', 'yyyy/mm/dd')), my_table.timestamp) > 30 then my_table.id else null end self_parent_id from my_table ) base_sub ) sub group by sub.time_group_parent_id, sub.cusip
source share