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
नोट:यह प्रत्येक जानवर के लिए गिनती फिर से शुरू करेगा - जो कि आप जो करना चाहते हैं उसका वास्तविक इरादा प्रतीत होता है। समस्या की परिभाषा थोड़ी मुश्किल है यदि आप चाहते हैं कि समूह जानवरों से अलग हों, लेकिन वृद्धिशील हों। एक तरीका है:
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;