繁体   English   中英

从 to-be-found-row +1 中查找具有相同字段值的另一行的所有行

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

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

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

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

从上面的示例表中,这将返回:

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 技能不足以解决这样的查询。

提示:该表在 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

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

select t1.*
from t t1
join t t2 on t2.MediaIDdec = t1.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;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM