2013-03-04 39 views
-1

我有這個表是這樣的:如何獲得TSQL中第一列的輸入結束?

Sequence 
2089697 
2089738 
2089838 
2090368 
2090400 

我想有另一列

Sequence; EndSequence 
2089697; 2089737 
2089738; 2089837 
2089838; 2090367 
2090368; 2090399 
2090400; null 

的EndSequence將是順序列的下一個記錄的結束。

+0

你使用的是什麼版本的SQL Server? – 2013-03-04 05:32:48

回答

1

您可以將表加入自己,其中連接中的條件是匹配右側的記錄大於左側記錄的值。然後通過在左側和聚集在右邊最小值的數值組:

SELECT l.Sequence, MIN(r.Seqence)-1 "EndSequence" 
FROM table l 
LEFT JOIN table r ON r.Sequence > l.Sequence 
GROUP BY l.Sequence 
3

對於SQL Server 2005/2008

WITH records 
AS 
(
    SELECT Sequence, 
      ROW_NUMBER() OVER (ORDER BY Sequence ASC) rn 
    FROM TableName 
) 
SELECT a.Sequence, b.Sequence - 1 EndSequence 
FROM records a 
     LEFT JOIN records b 
      ON a.rn+1 = b.rn 

對於SQL SERVER 2012

SELECT SEQUENCE, 
     LEAD(SEQUENCE) OVER (ORDER BY SEQUENCE) - 1 EndSequence 
FROM TableName 
+1

很好地使用新的2012 LEAD關鍵字 – 2013-03-04 05:38:53

+1

+1。很好的答案。 – 2013-03-04 05:47:37

相關問題