我有以下查询(在此论坛上找到here的示例),该查询生成序列号以标记位置中的每个更改。
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
;
现在我想只保留那些指示每个ID通过不同位置的顺序路径的行。如何相应地过滤数据,以便生成以下结果:
ID Location
1 1
1 2
1 1
1 2
1 3
2 1
2 2
2 1
2 2
2 3
有没有办法实现他的?
答案 0 :(得分:0)
您似乎想删除相邻的重复项:
SELECT t.ID, t.col1, t.Location
FROM (SELECT t.*,
(CASE WHEN Location = lag(Location) OVER (order by ID, col1) THEN 0
ELSE 1
END) x
FROM t
) t
WHERE x = 1
ORDER BY ID, col1;
我使用了你的查询结构。我实际上会把它写成:
SELECT t.ID, t.col1, t.Location
FROM (SELECT t.*,
lag(Location) OVER (order by ID, col1) as prev_location
FROM t
) t
WHERE prev_location is NULL or prev_location <> location
ORDER BY ID, col1;