如何从时钟输出系统中的员工时钟获取持续时间

时间:2017-03-27 05:38:15

标签: sql sql-server

我目前正努力从钟表输出系统的时钟中获取每位员工的持续时间。   基本上我有一个事务表,它将所有时钟保存在时钟输出信息中。 例如,表记录如下所示:

    Name        |       Time           |  Action 
 employee A     |   20170327 08:30:00  |   in 
 employee B     |   20170327 08:35:00  |   in
 employee A     |   20170327 12:30:00  |   out 
 employee A     |   20170327 13:20:00  |   in 
 employee B     |   20170327 17:30:00  |   out 
 employee A     |   20170327 17:20:00  |   out 
 employee C     |   20170327 09:00:00  |   in

对于tap或clock out中的每个时钟,将会有一条记录插入此表中,我想获得同一个人最近的两条记录之间的持续时间,因此我想得到的查询结果将是是这样的:

   Name   |    Duration From    |   Duration To
    A     |  20170327 08:30:00  | 20170327 12:30:00
    A     |  20170327 13:20:00  | 20170327 17:20:00
    B     |  20170327 08:35:00  | 20170327 17:30:00
    C     |  20170327 09:00:00  |   NULL

这是我到目前为止的查询:

    Select name,min(StartTime) as DurationFrom,max(EndTime) as DurationTo
from 
    (select name, case Action when 'in' then time end as startTime,
                 case Action when 'out' then time end as endTime 
from dbo.transaction)main
    group by name

这是我到目前为止的结果:

   Name   |    Duration From    |   Duration To
    A     |  20170327 08:30:00  | 20170327 17:20:00
    B     |  20170327 08:35:00  | 20170327 17:30:00
    C     |  20170327 09:00:00  |   NULL

有人可以帮我解决这个问题吗?非常感谢提前。

1 个答案:

答案 0 :(得分:0)

你需要加入所有水龙头才能使用水龙头。

select s.name,  s.[time]  as startTime, min(e.[time]) as endTime 
from dbo.[transaction] s
left join dbo.[transaction] e
on s.name = e.name 
and e.Action='out'
and s.[time]< e.[time]
where s.Action='in'
group by s.name, s.[time]