用于计算事件之间的时间的日志事件处理查询

时间:2016-10-20 03:09:18

标签: sql sql-server

使用SQL Server 2014:

我正在尝试构建一个计算日志表中特定事件之间的时间的查询。

例如,请考虑下表:

+-----------+-------+------+-------+------------------+
| PK_INT_ID | EmpID | Name | Event | DateTime         |
+-----------+-------+------+-------+------------------+
| 1         | 5     | Mike | In    | 2016-10-12 14:05 |
+-----------+-------+------+-------+------------------+
| 2         | 4     | Jane | In    | 2016-10-12 14:08 |
+-----------+-------+------+-------+------------------+
| 3         | 4     | Jane | Out   | 2016-10-12 15:08 |
+-----------+-------+------+-------+------------------+
| 4         | 5     | Mike | Out   | 2016-10-12 16:05 |
+-----------+-------+------+-------+------------------+
| 5         | 5     | Mike | In    | 2016-10-13 08:15 |
+-----------+-------+------+-------+------------------+
| 6         | 5     | Mike | In    | 2016-10-13 08:30 |
+-----------+-------+------+-------+------------------+
| 7         | 4     | Jane | In    | 2016-10-13 08:31 |
+-----------+-------+------+-------+------------------+
| 8         | 4     | Jane | Out   | 2016-10-13 16:31 |
+-----------+-------+------+-------+------------------+
| 9         | 5     | Mike | In    | 2016-10-14 08:10 |
+-----------+-------+------+-------+------------------+
| 10        | 5     | Mike | Out   | 2016-10-14 15:10 |
+-----------+-------+------+-------+------------------+

我尝试创建的查询需要计算以下输出:

+------------+-------+------+--------------+
| Date       | EmpID | Name | Hours Worked |
+------------+-------+------+--------------+
| 2016-10-12 | 4     | Jane | 1            |
+------------+-------+------+--------------+
| 2016-10-12 | 5     | Mike | 2            |
+------------+-------+------+--------------+
| 2016-10-13 | 4     | Jane | 8            |
+------------+-------+------+--------------+
| 2016-10-13 | 5     | Mike | NULL         |
+------------+-------+------+--------------+
| 2016-10-14 | 4     | Mike | 7            |
+------------+-------+------+--------------+

获得此输出的最有效查询和索引策略是什么?

此类日志事件处理查询是否有任何特殊模式名称?

1 个答案:

答案 0 :(得分:0)

假设每个empid每天有一个进出组合,你可以使用

select cast(datetime as date) dt,empid,name,
datediff(hour, 
         max(case when event = 'In' then datetime end),
         max(case when event = 'Out' then datetime end)
         ) hours_worked
from t
group by cast(datetime as date),empid,name

计算列(hours_worked)将是null,以防在给定日期有2个或2个。