如果我理解正确,您可以使用lead(),然后使用一些过滤逻辑。首先,分配新的动作:
select t.*,
(case when (actionid, next_actionid) = ('wokeUp', 'snoozedAlarm')
then 'wokeup and snoozed'
when (actionid, next_actionid, next2_actionid) = ('wokeUp', 'ateBreakfast', 'brushedTeeth')
then 'started day'
else actionid
end) as action,
from (select t.*,
lead(actionId, 1) over (partition by person, day order by id) as next_actionid,
lead(actionId, 2) over (partition by person, day order by id) as next2_actionid
from t
) t;
接下来,使用此信息进行过滤:
with newactions as (
select t.*,
(case when (actionid, next_actionid) = ('wokeUp', 'snoozedAlarm')
then 'wokeup and snoozed'
when (actionid, next_actionid, next2_actionid) = ('wokeUp', 'ateBreakfast', 'brushedTeeth')
then 'started day'
else actionid
end) as action,
(case when (actionid, next_actionid) = ('wokeUp', 'snoozedAlarm')
then 2
when (actionid, next_actionid, next2_actionid) = ('wokeUp', 'ateBreakfast', 'brushedTeeth')
then 1
else 0
end) as duration
from (select t.*,
lead(actionId, 1) over (partition by person, day order by id) as next_actionid,
lead(actionId, 2) over (partition by person, day order by id) as next2_actionid
from t
) t
)
select na.*
from (select na.*,
lag(duration) over (partition by person order by id) as prev_duration,
lag(duration) over (partition by person order by id) as prev2_duration
from newactions na
) na
where not (prev_duration >= 1 or
prev2_duration >= 2
)