我有一张或多或少像这样的桌子:

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

我希望SELECT在同一组中具有相邻位置的行的组合。例如,给定上表,查询的输出应为:
+----------+-------+
| position | group |
+----------+-------+
| 5        | b     |
+----------+-------+
| 6        | b     |
+----------+-------+

性能有点问题,因为表有15亿行,但是position和group都是索引的,所以它比较快。对如何编写此查询有何建议?我不知道从哪里开始,因为我不知道如何编写包含多行输出的WHERE语句。

最佳答案

只需使用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);

关于sql - SQL查找具有相邻编号的行,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/53135730/

10-11 04:45