首页 > 解决方案 > 从 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 之后排序。

非常感谢您的帮助。

标签: sqlsql-servertsqlsubquerywindow-functions

解决方案


如果您发现join基于解决方案更容易消化

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

推荐阅读