如何在SQL Server中减去两个数据条目

时间:2011-04-13 20:07:01

标签: sql sql-server database

在我的数据库中,有一个表包含(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

2 个答案:

答案 0 :(得分:2)

这里的TestData CTE纯粹是出于测试目的。另外,我注意到您的数据存在错误。最后我检查14:15 AM不是有效时间。它是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, 'Osama', '14:15', 'IN'
    Union All Select 4, 'Osama', '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'    

答案 1 :(得分:0)

如果您可以假设您的时间是连续的,那么您可以执行Max(TimeRecorded)。假设您的ID是顺序的。您可以控制具有检查约束的任何一个。

declare @test table (
    Id int, Name varchar(50), TimeRecorded time, TypeOfTimeRecording varchar(3)
)

insert into @test values (1, 'Osama', CONVERT(time, '12:15'), 'IN')
insert into @test values (2, 'Osama', CONVERT(time, '12:20'), 'OUT')
insert into @test values (3, 'Osama', CONVERT(time, '12:25'), 'IN')
insert into @test values (4, 'Osama', CONVERT(time, '12:30'), 'OUT')

 select testOut.Name
        ,testOut.TimeRecorded
        ,testIn.TimeRecorded
        ,DATEDIFF(minute, testIn.TimeRecorded, 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'