MSSQL计算许多条目和exitis之间的总时间

时间:2016-08-18 08:07:19

标签: sql sql-server

我想请教您如何计算许多出入口之间的总时间。示例表如下所示(对于一个用户):

Date_Time               | Event        | User
------------------------|--------------|---------
2016-08-01 09:19:11.000 | Reader entry | John D.
2016-08-01 10:00:56.997 | Reader exit  | John D.
2016-08-01 10:09:24.000 | Reader entry | John D.
2016-08-01 11:14:12.000 | Reader exit  | John D.
2016-08-01 12:41:15.997 | Reader entry | John D.
2016-08-01 12:45:28.000 | Reader exit  | John D.
2016-08-01 12:47:23.000 | Reader entry | John D.
2016-08-01 13:37:06.997 | Reader exit  | John D.
2016-08-01 13:38:54.997 | Reader entry | John D.
2016-08-01 13:43:01.000 | Reader exit  | John D.

我想计算给定人员在某一天从入境到退出所花费的总时间。在上面的例子中,对于约翰D.,它将在02:40:30。

我使用的是MSSQL 2012。

提前感谢您的帮助, 的Pawel

1 个答案:

答案 0 :(得分:2)

我使用LAG窗口功能

    select [user], sum(datediff(s,prev_date_time,date_time)) as seconds
      from 
       (select [user], date_time, Event,
              lag(Date_time) over (partition by [user] order by Date_time) as prev_date_time,
              lag(Event) over (partition by [user] order by Date_time) as prev_event
          from myTable) as t
     where Event = 'Reader exit'
       and prev_event = 'Reader entry'
   group by [user];

<强>输出

user    seconds
John D. 9876

那实际上是2:44:36,我不知道你是怎么得到的02:40:30。