1

I have a table that contains three fields: Top(int), Left(int), Text(varchar).

The data inside the table are as following:

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   

I want to get all the "Text" where (X - previous X) < 10 and (Y - previous Y) < 10

The result in this case should be: B, C, F, M, Z

Is it possible to to do that with SQL?

Thank you in advance

Reporter
  • 3,897
  • 5
  • 33
  • 47

1 Answers1

1

You can use lag if it is SQL Server >= 2012 as below:

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

But here order by column needs to be correct. For sure you will be having an identity or sort column which you can use in order by

for Sql Server 2008 you can try as below:

;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
Kannan Kandasamy
  • 13,405
  • 3
  • 25
  • 38