如何计算SQL中Night Shift Employee的总工时,先进和后退

时间:2016-01-11 08:11:06

标签: sql sql-server sql-server-2012

如果夜班员工像​​5:30 Pm到第二天早上2:30。所以我无法计算..

转换表

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

员工LogInTable

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

使用此查询

  select UserId=t.UserId,LogDate, [LogIn] = Min(t.LogDate),LogOut = Max(t.LogDate), t.LogDate FROM (SELECT *, RowNum = ROW_NUMBER() OVER (PARTITION BY UserId, C1 ORDER BY LogDate)FROM  LoginTable ) t  group by t.User,t.LogDate

我得到了结果:

 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

如果我使用此查询只需在Logout for Night Shift中添加1天,那么我可以获得第二天登录信息

 select UserId,[date], min(convert(char(5), [Login], 108))as FirstIN,min(convert(char(5),DATEADD(day,1, LogOut),108))  as LastOUT   from  
 LoginTable  group by UserId,[date] 

我尝试了Min,Max,DateAdd,DateDiff,但我得错了输出:

  EmpId     date           FirstIN  LastOUT
  2267    2016-01-04        20:52   22:09
  2267    2016-01-05        00:35   00:35 

但我想要输出:

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

可以为此提供任何帮助?????

1 个答案:

答案 0 :(得分:1)

如果您将LogIn日期从午夜(0 = 00:00)和班次开始之间的秒数移动,它将获得班次的日期,并且可以在GROUP BY中使用。

查询:

WITH s AS (
SELECT s.UserID, e.LogIn, e.LogOut
    , [DATE] = CAST(DATEADD(minute, DATEDIFF(minute, s.[Start], 0), e.LogIn) as date)
FROM @Shifts s
INNER JOIN @Employees e ON s.UserID = e.UserID) SELECT s.UserID, [DATE], FirstIN = CAST(MIN(LogIn) as time), LastOut = CAST(MAX(LogOut) as time)FROM s GROUP BY s.UserID, [DATE];