问题描述
|
在我的数据库中,有一个表包含(ID,名称,时间,类型)
ID Name Time Type
1 Osama 12:15 AM IN
2 Osama 12:20 AM OUT
3 Osama 14:15 AM IN
4 Osama 14:20 AM OUT
我需要构造一个查询以输出时差(OUT-IN)
Name,OUT-IN
例:
Osama,5
Osama,5
解决方法
这里的
TestData
CTE仅用于测试目的。另外,我注意到您的数据有误。最后我检查了“ 4”不是有效时间。它是14:15
(通过24小时制)或2:15 AM
(通过12小时制)。另外,此解决方案将需要SQL Server 2005或更高版本。
With TestData As
(
Select 1 As Id,\'Osama\' As Name,\'12:15\' As Time,\'IN\' As Type
Union All Select 2,\'Osama\',\'12:20\',\'OUT\'
Union All Select 3,\'14:15\',\'IN\'
Union All Select 4,\'14:20\',\'OUT\'
),CheckInCheckOut As
(
Select Id,Name,Time,Type,Row_Number() Over ( Partition By Name,Type Order By Time ) As Num
From TestData
)
Select C1.Name,DateDiff( mi,CAST(C1.Time as datetime),Cast(C2.Time As datetime) ) As [OUT-IN]
From CheckInCheckOut As C1
Join CheckInCheckOut As C2
On C2.Name = C1.Name
And C2.Type = \'OUT\'
And C2.Num = C1.Num
Where C1.Type = \'IN\'
,如果可以确定您的时间是连续的,则可以执行Max(TimeRecorded)。这假设您的ID是连续的。您可以控制带有检查约束的任何一个。
declare @test table (
Id int,Name varchar(50),TimeRecorded time,TypeOfTimeRecording varchar(3)
)
insert into @test values (1,CONVERT(time,\'12:15\'),\'IN\')
insert into @test values (2,\'12:20\'),\'OUT\')
insert into @test values (3,\'12:25\'),\'IN\')
insert into @test values (4,\'12:30\'),\'OUT\')
select testOut.Name,testOut.TimeRecorded,testIn.TimeRecorded,DATEDIFF(minute,testOut.TimeRecorded) as [Out - In]
from @test testOut
inner join
@test testIn on testIn.Id = (select MAX(Id) from @test where Name = testOut.Name and Id < testOut.Id and TypeOfTimeRecording = \'IN\')
where testOut.TypeOfTimeRecording = \'OUT\'