SQL查找具有相邻数字的行

标签 sql postgresql

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

+----------+-------+
| 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/

相关文章:

node.js - 在 node.js 中使用 pg-postgres 的正确方法?

sql - 是否可以在 Postgres 中仅在 2 列之一发生冲突时插入?

postgresql - 如何处理返回触发器的过程中的 jOOQ 折旧警告?

mysql - 从表中选择行,其中两列形成一个不同的集合并按第三个字段排序

MySQL插入相同的值

php - 在 PHP 中将 2 个不同表中的 1 列匹配在一起

postgresql - Postgres FOR 循环

SQL 查询用 JOINS 或其他东西替换 UNION ALL

mysql - 重复的 MySQL 行

sql - 如何将列名转换为多行?