【发布时间】:2018-08-27 21:18:17
【问题描述】:
我有以下查询(在此论坛上找到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
有没有办法实现他的?
【问题讨论】:
标签: sql sql-server filtering