lag()
を使用する および累積合計:
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
注:これにより、各動物のカウントオーバーが再開されます。これは、実行したいことの実際の意図のようです。グループを動物ごとに分けたいが、段階的にしたい場合、問題の定義は少し注意が必要です。 1つの方法は次のとおりです:
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;