你可以嘗試像
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
還能有每個用戶的多個條目(登錄/註銷)表中?你想看看所有的時期嗎? – 2010-04-26 04:43:03
哦,是的。所以,User1每天可能會有50次I,O操作。 – Lp1 2010-04-26 12:39:08