如果你的结构正是你所提供的样品中,和你没有背靠背挥笔(如员工可能刷他的卡两次想第一个未提交),那么你可以做这样的查询:
WITH InOut (empId, EntryTime, ExitTime) as
(SELECT empId ,
a1.EntryTime ,
(SELECT MIN(a2.ExitTime)
FROM attendance a2
WHERE a1.empId = a2.empId
AND a1.EntryTime < a2.ExitTime
)
FROM attendance a1
WHERE EntryTime IS NOT NULL
)
SELECT empId ,
EntryTime ,
ExitTime,
DATEDIFF(Minute, EntryTime, ExitTime) AS minutes FROM InOut;
编辑: 我不明白您的评论。下面是一个完整的示例:
DECLARE @attendance TABLE
(
EMPID INT ,
EntryTime DATETIME NULL ,
ExitTime DATETIME NULL
);
INSERT @attendance
(EMPID, EntryTime, ExitTime)
VALUES (11769, '2015-02-01 08:00:00', NULL),
(11769, NULL, '2015-02-01 13:00:00'),
(11769, '2015-02-02 09:00:00', NULL),
(11769, NULL, '2015-02-02 12:00:00'),
(11769, '2015-02-03 08:00:00', NULL),
(11769, NULL, '2015-02-03 13:00:00'),
(1, '2015-02-01 08:10:00', NULL),
(1, NULL, '2015-02-01 13:10:00'),
(1, '2015-02-02 09:10:00', NULL),
(1, NULL, '2015-02-02 12:10:00'),
(1, '2015-02-03 08:10:00', NULL),
(1, NULL, '2015-02-03 13:10:00'),
(2, '2015-02-01 08:30:00', NULL),
(2, NULL, '2015-02-01 13:30:00'),
(2, '2015-02-02 09:30:00', NULL),
(2, NULL, '2015-02-02 12:30:00'),
(2, '2015-02-03 08:30:00', NULL);
WITH InOut (empId, EntryTime, ExitTime)
AS (SELECT EMPID ,
a1.EntryTime ,
(SELECT MIN(a2.ExitTime)
FROM @attendance a2
WHERE a1.EMPID = a2.EMPID
AND a1.EntryTime < a2.ExitTime
)
FROM @attendance a1
WHERE EntryTime IS NOT NULL
)
SELECT empId ,
EntryTime ,
ExitTime ,
DATEDIFF(MINUTE, EntryTime, ExitTime) AS minutes
FROM InOut;
,其结果是:
empId EntryTime ExitTime minutes
11769 2015-02-01 08:00:00.000 2015-02-01 13:00:00.000 300
11769 2015-02-02 09:00:00.000 2015-02-02 12:00:00.000 180
11769 2015-02-03 08:00:00.000 2015-02-03 13:00:00.000 300
1 2015-02-01 08:10:00.000 2015-02-01 13:10:00.000 300
1 2015-02-02 09:10:00.000 2015-02-02 12:10:00.000 180
1 2015-02-03 08:10:00.000 2015-02-03 13:10:00.000 300
2 2015-02-01 08:30:00.000 2015-02-01 13:30:00.000 300
2 2015-02-02 09:30:00.000 2015-02-02 12:30:00.000 180
2 2015-02-03 08:30:00.000 NULL NULL
当时间不匹配会发生什么? –
我只想获得特定员工当天的第一个和最后一个员工..时间不匹配..员工可以有多个出勤和多个入库 –
所有我想要的第一个和最后一个出口...多数民众赞成在所有和在此基础上,我想计算的工作时间..我有点困惑现在..一点帮助将不胜感激..我是新手 –