Utilisez lag()
et somme cumulée :
with query as (
select w.*,
sum(case when week < prev_week + 2 then 0 else 1 end) over (partition by animal order by week) as grp
from (select w.*,
lag(week) over (partition by animal order by week) as prev_week
from test.walk w
) w
)
select
animal, week, grp,
dense_rank() over (order by animal, grp) as grp2
from query
Remarque :Cela redémarrera le comptage pour chaque animal - ce qui semble être l'intention réelle de ce que vous voulez faire. La définition du problème est un peu délicate si vous voulez que les groupes soient séparés par animal, mais qu'ils soient incrémentaux. Une méthode est :
select w.*,
sum(case when prev_week = week then 0 else 1 end) over (order by min_week, animal, week) as grp
from (select w.*,
lag(week) over (partition by animal order by week) as prev_week,
min(week) over (partition by animal) as min_week
from test.walk w
) w;