SQL Server 2012 现在让自联接和聚合变得有点不必要了。此解决方案处理同一用户的多次登录。
DECLARE @t TABLE(UserID INT, [Type] TINYINT, InsertDate DATETIME);
INSERT @t VALUES
(2134,1,'20120803 10:12:24.350'),
(2134,2,'20120803 10:29:21.550'),
(2134,1,'20120803 11:22:24.350'),
(2134,2,'20120803 11:47:21.550'),
(5915,1,'20120802 14:57:57.453'),
(5915,2,'20120802 16:59:00.477');
;WITH x AS (
SELECT UserID, [Type], InsertDate, Prev = LAG(InsertDate, 1) OVER
(PARTITION BY UserID ORDER BY InsertDate) FROM @t
)
SELECT UserID, DATEDIFF(SECOND, Prev, InsertDate) FROM x WHERE [Type] = 2;
-- or if you want cumulative time per user even if there are multiple login events:
;WITH x AS (
SELECT UserID, [Type], InsertDate, Prev = LAG(InsertDate, 1) OVER
(PARTITION BY UserID ORDER BY InsertDate) FROM @t
)
SELECT UserID, SUM(DATEDIFF(SECOND, Prev, InsertDate))
FROM x WHERE [Type] = 2 GROUP BY UserID;
在以前的版本中,您可以使用更复杂的:
;WITH x AS
(
SELECT UserID, [Type], InsertDate,
rn = ROW_NUMBER() OVER (PARTITION BY UserID ORDER BY InsertDate)
FROM @t
)
SELECT x.UserID, DATEDIFF(SECOND, x.InsertDate, y.InsertDate)
FROM x INNER JOIN x AS y
ON x.UserID = y.UserID
AND x.rn = y.rn - 1
WHERE x.Type = 1
AND y.Type = 2;