有如下原始表数据,现需要根据Id列,将相邻两条记录差值小于等于4的记录查询出来。
数据库:Oracle
使用Oracle的分析函数 lead over 和 lag over,最终 SQL 如下:
select t2.*
from (select t1.id,
t1.firstname,
t1.lastname,
(case t1.prev_val
when null then
null
else
t1.id - t1.prev_val
end) as prev_diff,
(case t1.next_val
when null then
null
else
t1.next_val - t1.id
end) as next_diff
from (select t.id,
t.firstname,
t.lastname,
lag(t.id) over(order by t.id asc) as prev_val,
lead(t.id) over(order by t.id asc) as next_val
from SHANHY_REACTOR_EXAMPLE_CUSTOMER t) t1) t2
where t2.prev_diff <= 4 or t2.next_diff <= 4;
SQL 执行结果如下:
(END)