根据日期时间列左连接到同一 table 中的上一条记录

left join to previous record in same table based on datetime column

我有一个 table 包含会员访问时间的详细信息。

我想根据日期时间列 table 左连接到上一条记录

当我查看访问数据时,我还想查看他们上次访问的时间,以便计算两次访问之间的时间间隔。 VisitDateTime 列是日期时间数据类型。 table 中可能有数亿行。

示例数据:

MemberID VisitDateTime
1        2016-01-01 10:00:00.000
2        2016-01-01 10:01:00.000
1        2016-01-01 11:00:00.000
2        2016-01-01 11:30:00.000
3        2016-01-01 11:45:00.000
1        2016-01-01 11:50:00.000

因此,我正在尝试将 table 加入自身,该成员的前一个 Visit.VisitDateTime 显示为 PreviousVisitDateTime 列:

想要的结果:

MemberID VisitDateTime           PreviousVisitDateTime
1        2016-01-01 10:00:00.000 null
2        2016-01-01 10:01:00.000 null
1        2016-01-01 11:00:00.000 2016-01-01 10:00:00.000
2        2016-01-01 11:30:00.000 2016-01-01 10:01:00.000
3        2016-01-01 11:45:00.000 null
1        2016-01-01 11:50:00.000 2016-01-01 11:00:00.000

但我什至无法想象我会怎么做。

您没有指定 SQL Server 的版本,因此对于 SQL Server 2012 及更高版本:

CREATE TABLE #Test (MemberID INT, VisitDateTime DATETIME);

INSERT INTO #Test(MemberID, VisitDateTime) VALUES
(1, '2016-01-01 10:00:00.000'),
(2, '2016-01-01 10:01:00.000'),
(1, '2016-01-01 11:00:00.000'),
(2, '2016-01-01 11:30:00.000'),
(3, '2016-01-01 11:45:00.000'),
(1, '2016-01-01 11:50:00.000') 

SELECT MemberID
      ,VisitDateTime,
      LAG(VisitDateTime) OVER (PARTITION BY MemberID ORDER BY VisitDateTime) PreviousVisit FROM #Test
      ORDER BY VisitDateTime;


  MemberID    VisitDateTime           PreviousVisit
----------- ----------------------- -----------------------
1           2016-01-01 10:00:00.000 NULL
2           2016-01-01 10:01:00.000 NULL
1           2016-01-01 11:00:00.000 2016-01-01 10:00:00.000
2           2016-01-01 11:30:00.000 2016-01-01 10:01:00.000
3           2016-01-01 11:45:00.000 NULL
1           2016-01-01 11:50:00.000 2016-01-01 11:00:00.000

并模拟 2008 年的 LAG,尝试 Alternate of lead lag function in sql server 2008

如果你想用左连接来做:

SELECT a.MemberID, a.Visitdatetime,MIN(b.visitdatetime)
FROM #Test a
LEFT JOIN #Test b on b.MemberID=a.MemberID and b.visitDateTime < a.visitDateTime
GROUP BY a.MemberID,a.VisitDateTime
ORDER BY a.visitdatetime