如何找到SQL Server中的夜班员工的Firstin LastOut

时间:2016-01-29 11:43:15

标签: sql sql-server

我可以使用min(),max()从Day Shift员工中获得FirstIn - LastOut。但我有夜班员工的问题,如5:30 Pm到次日凌晨2:30。在同一天(第二天)他们将在下午5:30再次来。所以我无法计算..

Ex:转换表

  UserID     ShiftName    Start   End     
   2267     Night Shift-1  17:30  02:30 

Ex:员工表:

   UserID     LogIn                   LogOut                         LogDate
    2267   2016-01-04 20:52:08.000  2016-01-04 22:09:22.000   2016-01-04 00:00:00.000
    2267   2016-01-04 23:00:07.000  2016-01-04 23:00:07.000   2016-01-04 00:00:00.000
    2267   2016-01-05 00:35:46.000  2016-01-05 00:35:46.000   2016-01-05 00:00:00.000
    2267   2016-01-05 01:02:31.000  2016-01-05 03:57:16.000   2016-01-05 00:00:00.000
    2267   2016-01-05 18:43:50.000  2016-01-05 19:05:04.000   2016-01-05 00:00:00.000
    2267   2016-01-05 19:10:20.000  2016-01-05 22:26:00.000   2016-01-05 00:00:00.000
    2267   2016-01-05 23:27:24.000  2016-01-05 23:27:24.000   2016-01-05 00:00:00.000
    2267   2016-01-06 03:45:16.000  2016-01-06 03:45:16.000   2016-01-06 00:00:00.000

我想要输出:

        EmpId     date           FirstIN    LastOUT
        2267    2016-01-04        20:52      03:57
        2267    2016-01-05        18:43      03:45 

1 个答案:

答案 0 :(得分:1)

我认为这会更好地与lead()一起使用。获取同一行的“out”日期,然后进行聚合:

select userid, cast(logdate as date) as thedate,
       min(logdate), max(next_logdate)
from (select l.*,
             lead(logdate) over (partition by userid order by logdate) as next_logdate
      from logintable l
     ) l
where l.details = 'In'
group by userid, cast(logdate as date)
order by userid, cast(logdate as date);

(这不是转换回来,专注于逻辑的重要部分。)

注意:这假定'In'记录的下一个日志记录始终是'Out'记录。您的问题中的数据也是如此。