且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何使用MSSQL获取同一行中的当前行和下一行值

更新时间:2023-01-21 18:48:12

查看您的预期数据它看起来像是在日期订单。您可以在此基础上分配行号,以替换解决方案1中使用的ID(因此可以使用GUID作为ID),例如

Looking at your expected data it would appear to be in Date order. You can assign a row number on that basis which replaces the ID used in Solution 1 (and would therefore work with a GUID as the ID) e.g.
DECLARE @Table TABLE (ID INT IDENTITY(1,1) NOT NULL, TheDate DATE)

INSERT @Table(TheDate) 
values ('03-MAR-2017'), ('04-MAR-2017'), ('08-MAR-2017'), ('01-APR-2017')
;WITH CTE AS
(
    SELECT ID, TheDate
    ,ROW_NUMBER() OVER(ORDER BY TheDate) AS rn
    FROM @Table
)
SELECT CTE.ID, CTE.TheDate As Date1, NXT.TheDate As Date2
FROM CTE
LEFT OUTER JOIN CTE NXT ON NXT.rn = CTE.rn + 1

如果您有SQL Server 2012(不是Express版本)或更高版本(包括2014 Express),那么您可以使用Window函数(远neater)

If you have SQL Server 2012 (not the Express version) or a later version (including 2014 Express), then you can use Window functions instead (far neater)

SELECT ID, TheDate, LEAD(TheDate,1) OVER (ORDER BY TheDate) FROM @Table


这适用于您当前的数据;但是,如果你切换到GUID,你就可以自己了。



This works with your current data; however, you are on your own if you switch to a GUID

DECLARE @Table TABLE (ID INT IDENTITY(1,1) NOT NULL, TheDate DATE)

INSERT @Table(TheDate) 
values ('03/03/2017'), ('04/03/2017'), ('08/03/2017'), ('01/04/2017')

SELECT a.ID
     , Date1 = a.TheDate
     , Date2 = b.TheDate

FROM            @Table  a
LEFT OUTER JOIN @Table  b ON a.ID + 1 = b.ID

ORDER BY A.ID