基准表
id line_number
1 1232
2 1456
3 1832
4 2002
我希望将值添加到新表中,以便下一行的值成为新列中的值,最后一行的值相同。
我需要制作的最终输出是:
id line_number end_line_number
1 1232 1456
2 1456 1832
3 1832 2002
4 2002 2002
数据库是sql server。
真心感谢任何帮助。
由于
答案 0 :(得分:7)
在SQL Server 2012
之后,您可以像这样使用LEAD
。
;WITH BaseTable as
(
SELECT 1 id, 1232 line_number
UNION ALL SELECT 2 , 1456
UNION ALL SELECT 3, 1832
UNION ALL SELECT 4 , 2002
)
SELECT id,line_number,(LEAD(line_number,1,line_number) OVER(ORDER BY id ASC))
FROM BaseTable
对于以前的版本,请尝试此
;WITH BaseTable as
(
SELECT 1 id, 1232 line_number
UNION ALL SELECT 2 , 1456
UNION ALL SELECT 3, 1832
UNION ALL SELECT 4 , 2002
), OrderedBaseTable as
(
SELECT id,line_number,ROW_NUMBER() OVER(ORDER BY id asc) rw
FROM BaseTable
)
SELECT t1.id,t1.line_number,ISNULL(t2.line_number,t1.line_number) next_line_number
FROM OrderedBaseTable t1
LEFT JOIN OrderedBaseTable t2
ON t1.rw = t2.rw - 1
答案 1 :(得分:1)
试试这个
With T as (
Select id, line_number, Row_Number() OVER(Order By id) + 1 As TempId From TableName)
Select T1.id, T1.line_number, ISNULL(T2.line_number,T1.line_number) As end_line_number From T T1
Left Join T T2 on T2.id = T1.TempId
SQL小提琴Demo