Click here to Skip to main content
15,890,512 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I want a value from a previous row.

myTable with values

RowNo Name Salary
1 Alan 20000
2 Alan 22000
3 Alan 24000

I want to get the previous value from the last row e.g. 22000

I do not have a row number in my table so done the following


select ROW_NUMBER() over (ORDER BY Name) AS RowNo,
* from myTable
where Name = 'Alan'

Any ideas with sample code would be fantastic
Posted
Comments
Tomas Takac 28-Jan-15 11:04am    
Which database / version? SQL Server 2012 has nice windowing functions you can use.
Central_IT 28-Jan-15 11:07am    
I am using SQL Server 2008 and the code will be part of a function

1 solution

This should do it
SQL
WITH CTE AS (
  SELECT
    rownum = ROW_NUMBER() OVER (ORDER BY Name, RowNo),
    Salary, RowNo, Name
  FROM myTable
)
SELECT
  cur.RowNo, cur.Name, cur.Salary, ISNULL(prev.Salary,0)
FROM CTE cur
LEFT OUTER JOIN CTE prev on prev.rownum = cur.rownum - 1

You said there was no row number in your table but your data showed a RowNo... it doesn't really matter but you might want to change the ORDER BY clause. Edit - just re-read your question - apologies about my confusion on RowNo - ignore me :-)

This produces the following results:
ROWNO NAME SALARY COLUMN_3
1     Alan 20000  0 
2     Alan 22000  20000 
3     Alan 24000  22000 
 
Share this answer
 
v2
Comments
Central_IT 29-Jan-15 4:21am    
Works a treat.
Thank you for this.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900