我的表格如下:
id time_stamp evenid
1001 2017-09-05 09:35:00 1(in)
1002 2017-09-05 11:00:00 0(out)
我使用下面的查询,但得到的却不是确切的答案。错误第二天在所需的日期
;WITH InOut (empId, EntryTime, ExitTime,POINTID,EVENTID,Belongs_to) as
(SELECT emp_reader_id ,
a1.DT ,
( SELECT MIN(a2.DT)
FROM trnevents a2
WHERE a1.emp_reader_id = a2.emp_reader_id
AND a1.DT < a2.DT
),a1.DeviceSerialNumber,EVENTID,Belongs_to
FROM trnevents a1
)
SELECT empId ,
EntryTime ,
ExitTime,EVENTID, Belongs_to
,CONVERT( CHAR(11), '2017/12/30', 103 ) as StartDate
,CONVERT( CHAR(11), '2018/01/15', 103 ) as ToDate
,case when convert(time,dateadd(ms,DATEDIFF(SECOND, EntryTime, ExitTime)*1000,0),114) is not null
then convert(time,dateadd(ms,DATEDIFF(SECOND, EntryTime, ExitTime)*1000,0),114) else '00:00' end as Worked FROM InOut A
输出错误:第二天也是
EMP_NO INTIME OUTTIME DT WORKED
101 2018-01-08 09:11:14.000 2018-01-08 12:07:22.000 2018-01-08 02:56:08.0000000
101 2018-01-08 12:07:22.000 2018-01-08 14:35:33.000 2018-01-08 02:28:11.0000000
101 2018-01-08 14:35:33.000 **2018-01-09 09:14:00.000** 2018-01-08 18:38:27.0000000
101 2018-01-09 09:14:00.000 2018-01-09 14:28:23.000 2018-01-09 05:14:23.0000000
我想要的输出:
SL# Emp# Employee Name IN OUT Worked
2 107 Nisham M 24/Sep/2017 8:34:00AM 24/Sep/2017 10:15:00AM 01:41:00
24/Sep/2017 10:19:00AM 24/Sep/2017 12:20:00PM 02:01:00
24/Sep/2017 12:25:00PM 24/Sep/2017 12:54:00PM 00:29:00
24/Sep/2017 2:13:00PM 24/Sep/2017 2:14:00PM 00:01:00
24/Sep/2017 2:19:00PM 24/Sep/2017 5:25:00PM 03:06:00
10/Oct/2017 2:00:00PM 10/Oct/2017 2:52:00PM 00:52:00
10/Oct/2017 3:15:00PM NULL -
11/Oct/2017 8:26:00AM 11/Oct/2017 10:29:00AM 02:03:00
19/Oct/2017 1:59:00PM 19/Oct/2017 5:56:00PM 03:57:00
Total Shift Hours Total Basic Hours OT Normal Hours Total Hours Worked
210 159:20:00 00:00:00 159:20:00
我坚持到这里搜索大多数但没有获得所需的输出任何人的帮助
答案 0 :(得分:5)
根据to this answer,添加:
AND DATEDIFF(DAY, a1.DT, a2.DT) = 0
对于WHERE
条款,应确保开始日期和结束日期在同一天,但如果有人在午夜过夜会怎样?你的帖子也暗示你也把结束时间作为开始时间,所以你可以这样做:
AND a1.EVENTID = 1 AND a2.EVENTID = 0
如果两者都不合适,请进一步描述您的问题并提供更多样本数据。