I have the following query (example found here on this forum) that generates a sequence number to mark each change in Location.
WITH t(ID, col1 ,Location) AS (
select 1, 1 , 1 union all
select 1, 2 , 1 union all
select 1, 3 , 2 union all
select 1, 4 , 2 union all
select 1, 5 , 1 union all
select 1, 6 , 2 union all
select 1, 7 , 2 union all
select 1, 8 , 3 union all
select 2, 1 , 1 union all
select 2, 2 , 2 union all
select 2, 3 , 2 union all
select 2, 4 , 2 union all
select 2, 5 , 1 union all
select 2, 6 , 1 union all
select 2, 7 , 2 union all
select 2, 8 , 3
)
SELECT t.ID, t.col1, t.Location,
sum(x) OVER (partition by ID order by col1) sequence
FROM (
SELECT t.*,
CASE WHEN Location = lag(Location) OVER (order by ID, col1) THEN 0
ELSE 1
END x
FROM t
) t
ORDER BY ID, col1
;
Now I would like to keep only those rows that indicate the sequential path through the different locations for each ID. How can I filter the data accordingly so that the following result is generated:
ID Location
1 1
1 2
1 1
1 2
1 3
2 1
2 2
2 1
2 2
2 3
Is there a way to achieve his?