Вы можете попробовать что-то вроде
DECLARE @Table TABLE(
EmpNum Int,
[User] VARCHAR(10),
Action VARCHAR(1),
Updatetime DATETIME
)
INSERT INTO @Table SELECT 1,'User1','I','2010-01-01 23:00:00:000'
INSERT INTO @Table SELECT 1,'User1','O','2010-01-01 23:05:00:000'
INSERT INTO @Table SELECT 1,'User1','I','2010-01-01 23:10:00:000'
INSERT INTO @Table SELECT 1,'User1','O','2010-01-01 23:25:00:000'
SELECT *,
DATEDIFF(mi, InTime, OutTime) Period
FROM (
SELECT EmpNum,
[User],
UpdateTime InTime,
( SELECT TOP 1
Updatetime
FROM @Table
WHERE EmpNum = t.EmpNum
AND Action = 'O'
AND Updatetime > t.Updatetime
ORDER BY Updatetime
) OutTime
FROM @Table t
WHERE Action = 'I'
) sub
выход
EmpNum User InTime OutTime Period
----------- ---------- ----------------------- ----------------------- -----------
1 User1 2010-01-01 23:00:00.000 2010-01-01 23:05:00.000 5
1 User1 2010-01-01 23:10:00.000 2010-01-01 23:25:00.000 15