运行SQL Server 2008,我绝对是一个新的SQL用户。
我有一个包含4列的表:
EmpNum, User, Action, Updatetime
用户登录并退出系统,它已在数据库中注册。例如,如果user1登录到系统,然后在5分钟后退出,则一个简单的查询(select * from update)将如下所示:
EmpNum User Action Updatetime
1 User1 I 2010-01-01 23:00:00:000
1 User1 O 2010-01-01 23:05:00:000
我正在尝试查询Empnum,用户,操作,我(及时),O(出时间)和总时间。
答案 0 :(得分:2)
您可以尝试类似
的内容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
答案 1 :(得分:0)
Select T1.EmpNum, T1.User, T1.UpdateTime As TimeIn
, (Select Min(T2.UpdateTime)
From Table As T2
Where T2.EmpNum = T1.EmpNum
And T2.User = T1.User
And T2.Action = 'O'
And T2.UpdateTime > T1.UpdateTime) As TimeOut
From Table As T1
Where Action = 'I'
编辑在评论中,您要求使用TimeWorked。由于您使用的是SQL Server 2008,因此可以使用外部应用来计算每个及时行的输出时间。然后使用DateDiff是一件简单的事。
Select T1.EmpNum, T1.User
, T1.UpdateTime As TimeIn
, TimeOut.UpdateTime As TimeOut
, DateDiff(mi, T1.UpdateTime, TimeOut.UpdateTime) As TimeWorkedInMinutes
From Table As T1
Outer Apply (
Select Min(T2.UpdateTime) As UpdateTime
From Table As T2
Where T2.EmpNum = T1.EmpNum
And T2.User = T1.User
And T2.Action = 'O'
And T2.UpdateTime > T1.UpdateTime
) As TimeOut
Where Action = 'I'