[英]How to subtract two data entries in SQL Server
在我的數據庫中,有一個表包含(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純粹是出於測試目的。 另外,我注意到您的數據存在錯誤。 最后我檢查了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'
如果你可以假設你的時間是連續的,你可以做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'
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.