获取同一列中两行的时间跨度

Chr*_*s B 2 sql t-sql sql-server sql-server-2012

我在SQL Server 2012中有一个表跟踪登录和注销时间,如下所示:

UserId    Type    InsertDate
2134      1       20120803 06:32:02.230
2134      1       20120803 10:12:24.350
2134      2       20120803 10:29:21.550
2134      2       20120803 14:10:34.220
5915      1       20120802 14:57:57.453
5915      2       20120802 16:59:00.477
Run Code Online (Sandbox Code Playgroud)

(类型1是登录,类型2是注销.)

我想查询此表 - 显示每个登录/注销对的计算出的时间跨度(以秒为单位)的用户ID的分组列表,因此我最终得到如下内容:

UserID    Duration 
2134      1017 
5915      7263
Run Code Online (Sandbox Code Playgroud)

更新:单个用户可以有多组登录/注销对,并且可能存在没有相应注销的登录.我想忽略没有相应值的登录或注销.

Aar*_*and 6

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;
Run Code Online (Sandbox Code Playgroud)

在以前的版本中,您可以使用更复杂的:

;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;
Run Code Online (Sandbox Code Playgroud)

  • 今天在sql server 2012中学到了一个新功能(Lag).很棒的答案! (3认同)