Search This Blog

Saturday, August 16, 2008

comparing current row with previos and next row in a table

you must define identity column or there should be an integer column to keep the sequence of the rows, or you can import the data into a temporary table with an additional identity column.

here is the script:

Create Table #Temp
(I_Col int identity(1,1)
,val1 int
)


Insert into #Temp values(10)
Insert into #Temp values(25)
Insert into #Temp values(67)
Insert into #Temp values(98)
Insert into #Temp values(11)

Select * From #Temp

I_Col (identity column)

Val1

1

10

2

25

3

67

4

98

5

11

Select Curr.val1 Current_Value
,
isnull(Prev.val1,0) Prev_Value
,
isnull(_Next.val1,0) Next_Value

From #Temp Curr
Left outer Join #Temp Prev On Prev.I_Col = Curr.I_Col -1
Left Outer Join #Temp _Next On _Next.I_Col = Curr.I_Col + 1

Current_Value

Prev_Value

Next_Value

10

0

25

25

10

67

67

25

98

98

67

11

11

98

0

No comments: