计算上一行之间的持续时间

时间:2016-06-09 07:16:53

标签: tsql sql-server-2012

我有一个SQL Server 2012表,其中包含以下数据:

Id; InstanceNo; ActionDate;              Text
-----------------------------------------------
1;  27500;      2016-04-15 13:39:11.843; Start
2;  27500;      2016-04-15 13:40:12.857; Step1
3;  27500;      2016-04-15 13:41:13.856; Step2
4;  27500;      2016-04-15 13:43:17.657; Step3
5;  27500;      2016-04-15 13:45:18.257; End
6;  29321;      2016-04-14 12:32:12.857; Start
7;  29321;      2016-04-14 12:40:17.247; Step1
8;  29321;      2016-04-15 09:18:19.156; End

Id是身份,表格由InstanceNo, ActionDate排序。

我想计算每行之间的持续时间。

问题是,每次有新实例No时,起始值应为'0'(而不是例如Id 5和Id 6之间的持续时间)

实际上,我正在使用此查询。它很慢(表中只有25000行),并且当它是一个新实例时不会从零开始:

SELECT 
    t1.ID, t1.InstanceNo, t1.ActionDate, t1.Text, 
    DATEDIFF(ss, x.ActionDate, t1.ActionDate) AS [Duration sec]
FROM 
    Tmp_Stat_Sepa t1
OUTER APPLY 
    (SELECT TOP 1 ActionDate 
     FROM Tmp_Stat_Sepa t2 
     WHERE t2.ID < t1.ID 
     ORDER BY t2.ID DESC) x

感谢您的支持。

1 个答案:

答案 0 :(得分:2)

你没有提到你想要哪些单位,所以我用了几秒钟。

CREATE TABLE #Test (
  Id INTEGER,
  InstanceNo INTEGER,
  ActionDate DATETIME,
  Text VARCHAR(10)
);

INSERT INTO #Test (Id, InstanceNo, ActionDate, Text) VALUES
  (1,  27500,      '2016-04-15 13:39:11.843', 'Start'),
  (2,  27500,      '2016-04-15 13:40:12.857', 'Step1'),
  (3,  27500,      '2016-04-15 13:41:13.856', 'Step2'),
  (4,  27500,      '2016-04-15 13:43:17.657', 'Step3'),
  (5,  27500,      '2016-04-15 13:45:18.257', 'End'),
  (6,  29321,      '2016-04-14 12:32:12.857', 'Start'),
  (7,  29321,      '2016-04-14 12:40:17.247', 'Step1'),
  (8,  29321,      '2016-04-15 09:18:19.156', 'End');


SELECT A.Id
      ,A.InstanceNo
      ,A.ActionDate
      ,A.Text
      ,COALESCE(DATEDIFF(SECOND, LastActionDate, ActionDate), 0) DiffInSeconds
FROM (
SELECT Id
      ,InstanceNo
      ,ActionDate
      ,Text
      ,LAG(ActionDate) OVER (PARTITION BY InstanceNo ORDER BY InstanceNo, ActionDate) LastActionDate 
      FROM #Test ) A


Id          InstanceNo  ActionDate              Text       DiffInSeconds
----------- ----------- ----------------------- ---------- -------------
1           27500       2016-04-15 13:39:11.843 Start      0
2           27500       2016-04-15 13:40:12.857 Step1      61
3           27500       2016-04-15 13:41:13.857 Step2      61
4           27500       2016-04-15 13:43:17.657 Step3      124
5           27500       2016-04-15 13:45:18.257 End        121
6           29321       2016-04-14 12:32:12.857 Start      0
7           29321       2016-04-14 12:40:17.247 Step1      485
8           29321       2016-04-15 09:18:19.157 End        74282

(8 row(s) affected)