基于当前的下一个/上一个记录

时间:2012-09-27 12:06:44

标签: sql sql-server-2008

我有一个表没有按任何列排序。如果我只知道当前的Id,有没有办法选择下一个/上一个记录? (我正在使用mssql)

Id     Label     Date
---------------------
1      label1    2011-01-10
7      label2    2011-01-15 -- how to get previous?
5      label3    2011-01-12 -- I know id of this record
10     label10   2011-01-25 -- how to get next?
12     label8    2011-01-13
2      label5    2011-01-29

提前致谢!

3 个答案:

答案 0 :(得分:4)

试试这个:

VALUES (1, 'label1', '2011-01-10'), (7, 'label2', '2011-01-15'),
       (5, 'label3', '2011-01-12'), (10, 'label10', '2011-01-25'),             
       (12, 'label8', '2011-01-13'), (2, 'label5', '2011-01-29')

select * from table007; 

Declare @inptID int=12;

;WITH CTE 
as
(
   select *, ROW_NUMBER() over (order by (select 0)) as rn 
   from table007
 )

select * 
from CTE 
where rn in( select rn-1 from CTE where id = @inptID)
union all
select * from CTE where rn in(select rn + 1 from CTE where id = @inptID);

SQL小提琴演示

DEMO

答案 1 :(得分:3)

如果没有按任何列排序,则没有明确的下一个或上一个记录。除了ORDER BY子句指定的数据外,SQL Server中的数据没有顺序。

答案 2 :(得分:2)

如果你真的想要你所附的列表中的前一个,这是一种方式。

declare @t table(Id int, Label varchar(10), Date date, s int identity(1,1))
insert @t (id, label, date) 
values(1,'label1','2011-01-10'),(7,'label2','2011-01-15'),
(5,'label3','2011-01-12'),(10,'label10','2011-01-25'),
(12,'label8','2011-01-13'),(2,'label5','2011-01-29')

--select the data with a self join

select t1.id as previous_id, t2.id, t2.Label, t2.Date, t3.id, t3.id as next_id
from @t t1
right join
@t t2 on t1.s + 1 = t2.s
left join
@t t3  on t2.s = t3.s - 1