MS SQL Server2012中的LEAD和LAG函数
为了理解这两个函数,可以先参考下面这两篇,http://www.cnblogs.com/insus/archive/2012/03/18/2404288.html 和 http://www.cnblogs.com/insus/archive/2012/03/23/2415041.html 可以获取在某一种排序下的某一记录的前一个值或后一个值。
现sQL Server 2012带来这两个函数,可以方便简捷实现。下面Insus.NET创建了一张临时表,并随意插入几笔记录。
CREATE TABLE [#tsource] ([id] int, [title] nvarchar(100))
INSERT INTO [#tsource] VALUES (2,'adfadf'),(3,'adfadf'),(7,'fdsdsfdadsffg'),(20,'xcdffd'),(7,'sdfgsdfg'),(40,'sdfsfdgsdfg'),(36,'sfdsdgsdfg')
INSERT INTO [#tsource] VALUES (2,'adfadf'),(3,'adfadf'),(7,'fdsdsfdadsffg'),(20,'xcdffd'),(7,'sdfgsdfg'),(40,'sdfsfdgsdfg'),(36,'sfdsdgsdfg')
下面SQL语句使用了LEAD和LAG函数:
SELECT [id],[title],
LAG([id]) OVER (ORDER BY [id]) AS [前一篇主键],
LEAD ([id]) OVER (ORDER BY [id]) AS [后一篇主键]
FROM [#tsource]
LAG([id]) OVER (ORDER BY [id]) AS [前一篇主键],
LEAD ([id]) OVER (ORDER BY [id]) AS [后一篇主键]
FROM [#tsource]
执行结果: