如何在MSSQL中选择行索引

时间:2017-07-27 08:51:09

标签: sql sql-server

我有一个包含三个字段的表: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   

我希望获得所有&#34; Text&#34; where (X - previous X) < 10 and (Y - previous Y) < 10

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

是否可以使用SQL执行此操作?

提前谢谢

1 个答案:

答案 0 :(得分:1)

如果是SQL Server&gt; = 2012,则可以使用滞后,如下所示:

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