user_012314112
user_012314112

Reputation: 344

get the previous row of a query

Doing a select I get a row, and I would want to get the previous row in the table.

create table t1
id char(3),
dat datetime
); 

id        dat
a  2014-04-21
b  2014-10-01
c  2014-10-15

select id from t1 where id='c'

and wanted to find the previous row i.e. b

Upvotes: 0

Views: 61

Answers (2)

Andriy M
Andriy M

Reputation: 77657

Get all the rows where id is not greater than the specified value, then limit the results to just the top two rows:

SELECT TOP (2)
  id
FROM
  t1
WHERE
  id <= 'c'
ORDER BY
  id DESC
;

Upvotes: 1

JohnS
JohnS

Reputation: 2052

What about:

DECLARE @id CHAR(3)
SET @id = 'c'
select 
  id 
from 
  table 
where 
  id=@id
  OR 
  id = (SELECT MAX(id) FROM table WHERE id < @id)

Upvotes: 2

Related Questions