2011-04-13 43 views
0

在我的數據庫中,有包含一個表(ID,姓名,時間,類型)如何減去在SQL Server中的兩個數據項

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 

回答

0

你可以做MAX(TimeRecorded)如果您沒有問題假設你的時間是SE序貫。這假定你的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' 
2

這裏的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'