You can use lag()
and a cumulative sum to define the groups and then aggregate. You can see the groups if you run this query:
select t.*,
sum(case when prev_date = prev_date2 then 0 else 1 end) over (order by date) as grp
from (select t.*,
lag(date) over (order by date) as prev_date,
lag(date) over (partition by first_id, second_id order by date) as prev_date2
from t
) t;
The logic is saying that a new group starts when the previous date does not have the same values of the two id columns.
Then the aggregation is:
with grps as (
select t.*,
sum(case when prev_date = prev_date2 then 0 else 1 end) over (order by date) as grp
from (select t.*,
lag(date) over (order by date) as prev_date,
lag(date) over (partition by first_id, second_id order by date) as prev_date2
from t
) t
)
select first_id, second_id, max(value), min(date), max(date)
from grps
group by grp
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…