查找所有行,其中另一行具有来自待发现行 +1 的相同字段值

Find all rows where there is another row which has in same field value from to-be-found-row +1

我有以下 table(为清楚起见,发出了不相关的字段和行):

customerID        MediaIDdec
--------------    ----------------------
.                 .
.                 .
.                 .
16253             453456691
36178             453456692
24352             671254112
81432             226124312
44513             226124313
31336             226124314
64231             453653811
.                 .
.                 .
.                 .

查询应 return 所有行 (row1),其中另一行 (row2) 中的 MediaIDdec 是 MediaIDdec (Row1) + 1。

根据上面的例子 table,这会 return:

16253             453456691     (because there is MediaIDdec+1 within row with customerID 36178)
81432             226124312     (because there is MediaIDdec+1 within row with customerID 44513)
44513             226124313     (because there is MediaIDdec+1 within row with customerID 31336)

老实说,我的 SQL 技能不足以解决这样的查询。

提示:table排在MediaIDdec之后。

非常感谢您的帮助。

您可以使用 exists:

select t.*
from mytable t
where exists (select 1 from mytable t1 where t1.MediaIDdec = t.MediaIDdec + 1)

如果 MediaIDdec 没有重复项,替代方案是 lead():

select *
from (
    select t.*, lead(MediaIDdec) over(order by MediaIDdec) leadMediaIDdec 
    from mytable t
) t
where leadMediaIDdec = MediaIDdec + 1

此方法使用 LEAD 函数

with lead_cte as (
    select *, lead(MediaIDdec) over (order by MediaIDdec)-MediaIDdec MediaIDdec_lead_diff
    from tTable)
select *
from lead_cte
where MediaIDdec_lead_diff=1;

如果您发现基于 join 的解决方案更容易理解

select t1.*
from t t1
join t t2 on t2.MediaIDdec = t1.MediaIDdec + 1