2012-09-27 33 views
3

我有一個不按任何列排序的表。如果我只知道當前的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 

在此先感謝!

+2

哪個版本?如果它是2012年的SQL Server比看**導致&&滯後** http://blog.sqlauthority.com/2011/11/15/sql-server-introduction-to-lead-and-lag-analytic-functions-引入在SQL服務器2012/ –

+0

我正在使用MS SQL 2008 – Vytalyi

+0

什麼是查詢用於獲得這些結果? –

回答

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 
+0

我不知道我有什麼專欄。我在桌上沒有這個coulmn。你想讓我創造它嗎? – Vytalyi

+0

標識,標籤,日期是列。我不想讓你創建新的列,我只是希望你用你所擁有的數據填充臨時表,然後你可以將這些行鏈接到前一行 –

+0

嗯,它適用於以前,謝謝!我怎樣才能修改它以同時看到下一個和上一個? – Vytalyi

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

+0

這個查詢有什麼問題...它不會返回我想要的...給我3分鐘,我會附上屏幕截圖 – Vytalyi

+0

不管你在問題中解釋了它的正確做法 – AnandPhadke

+0

你可以看截圖嗎?有任何想法嗎? – Vytalyi

3

如果沒有任何列進行排序,也沒有明確的下一個或前一個記錄。 SQL Server中的數據沒有順序,除了由ORDER BY子句指定的順序。

+0

正如你所說,不會有任何的順序,但根據我的理解,當數據存儲在內存中時,它只會附加到最後插入的行。所以這就是OP也想要的。我的意思是他想從堆中獲得上一行和下一行。 – AnandPhadke

相關問題