postgreSQL - SELECT id 仅相差一个的所有行

postgreSQL - SELECT all rows where an id only differs by one

我想 return 给定名称相同但 ID 在 psql 9.5.6 上仅相差一 (1) 的所有字段。

因此输入:

NAME     | ID
______________
Harry    | 12
Harry    | 13
Steven   | 14
Steven   | 16
Goldberg | 21

输出应该是:

   Harry

您可以使用 lead()lag():

select t.name
from (select t.*,
             lag(id) over (partition by name order by id) as prev_id
      from t
     ) t
where prev_id = id - 1;
    Select name  from table
       group by name having 
      max(id)- min(id)=1;

I think you asked id difference by each name as group by seeing the output. Can try the above.