简体   繁体   English

过滤顺序数据

[英]Filtering sequential data

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. 现在,我只想保留那些表示每个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? 有没有办法实现他的目标?

You seem to want to remove adjacent duplicates: 您似乎想删除相邻的重复项:

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;

I used the structure of your query. 我使用了查询的结构。 I would actually write this as: 我实际上会这样写:

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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM