我有这样的表:
Sequence
2089697
2089738
2089838
2090368
2090400
我想要另一个专栏
Sequence; EndSequence
2089697; 2089737
2089738; 2089837
2089838; 2090367
2090368; 2090399
2090400; null
EndSequence将是Sequence列的下一条记录的结尾。
答案 0 :(得分:3)
FOR 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
FOR SQL SERVER 2012
SELECT SEQUENCE,
LEAD(SEQUENCE) OVER (ORDER BY SEQUENCE) - 1 EndSequence
FROM TableName
答案 1 :(得分: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