如果你的結構正是你所提供的樣品中,和你沒有背靠背揮筆(如員工可能刷他的卡兩次想第一個未提交),那麼你可以做這樣的查詢:
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
當時間不匹配會發生什麼? –
我只想獲得特定員工當天的第一個和最後一個員工..時間不匹配..員工可以有多個出勤和多個入庫 –
所有我想要的第一個和最後一個出口...多數民衆贊成在所有和在此基礎上,我想計算的工作時間..我有點困惑現在..一點幫助將不勝感激..我是新手 –