我有一张看起来或多或少像这样的表格:
+----------+-------+
| position | group |
+----------+-------+
| 1 | a |
+----------+-------+
| 5 | b |
+----------+-------+
| 6 | b |
+----------+-------+
| 7 | c |
+----------+-------+
| 8 | b |
+----------+-------+
我想SELECT
在同一组中具有相邻位置的行的组合。例如,给定上表,查询的输出应该是:
+----------+-------+
| position | group |
+----------+-------+
| 5 | b |
+----------+-------+
| 6 | b |
+----------+-------+
性能有点问题,因为该表有 15 亿行,但位置和组都已编入索引,因此速度相对较快。关于如何编写此查询的任何建议?我不确定从哪里开始,因为我不知道如何编写涉及多行输出的 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查找具有相邻数字的行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53135730/