如何在 MSSQL 中选择行索引



我有一个包含三个字段的表:Top(int(,Left(int(,Text(varchar(。

表中的数据如下:

Text      X       Y
1       1000    250
2        700    100
A        618    300
B        620    400
C        625    405
F        623    402
D        400    410
M        300    415
Z        304    418   

我想获取所有"文本"where (X - previous X) < 10 and (Y - previous Y) < 10

在这种情况下,结果应该是:B, C, F, M, Z

是否可以使用 SQL 做到这一点?

提前谢谢你

如果是 SQL Server>= 2012,则可以使用 lag,如下所示:

Select * from (
Select *,PrevX = lag(X) over(order bY [Text]),
PrevY= lag(Y) over(order by [Text]) from yourtable
) a
where a.x-a.prevx < 10 and a.y-a.prevy <10

但是这里按列排序需要正确。当然,您将拥有一个标识或排序列,您可以按顺序使用

对于 Sql Server 2008,您可以尝试如下:

;With cte as (
Select *,RowN = Row_Number() over(order bY [Text])) from yourtable
) Select * from cte c1
left Join cte c2
on c1.RowN = C2.RowN-1
where c1.x-c2.X < 10 and C1.y-c2.y <10

最新更新