SQL查找具有相邻编号的行

时间:2018-11-03 21:37:35

标签: sql postgresql

我有一个看起来或多或少像这样的表:

+----------+-------+
| position | group |
+----------+-------+
| 1        | a     |
+----------+-------+
| 5        | b     |
+----------+-------+
| 6        | b     |
+----------+-------+
| 7        | c     |
+----------+-------+
| 8        | b     |
+----------+-------+

我要SELECT行的组合在同一组中具有相邻位置。例如,给定上面的表,查询的输出应为:

+----------+-------+
| position | group |
+----------+-------+
| 5        | b     |
+----------+-------+
| 6        | b     |
+----------+-------+

性能有点问题,因为该表有15亿行,但是位置和组都已索引,因此相对较快。关于如何编写此查询的任何建议?我不确定从哪里开始,因为我不知道如何编写涉及多行输出的WHERE语句。

3 个答案:

答案 0 :(得分:2)

只需使用lag()lead()

select t.*
from (select t.*,
             lag(group) over (order by position) as prev_group,
             lead(group) over (order by position) as next_group
      from t
     ) t
where prev_group = group or next_group = group;

如果“相邻”是指位置相差一个(而不是最接近的值),那么我会选择exists

select t.*
from t
where exists (select 1 from t t2 where t2.group = t.group and t2.position = t.position - 1) or
      exists (select 1 from t t2 where t2.group = t.group and t2.position = t.position + 1);

答案 1 :(得分:0)

select distinct T1.position, T2.group from
T as T1
inner join
T as T2
on(T1.group=T2.group and t2.position=t1.position+1)

答案 2 :(得分:0)

我会这样子选择:

select * from mytable m1
where (select count(*) from mytable m2 where m2.position = m1.position + 1 and m2.group = m1.group) > 0
相关问题