2010-11-22 57 views
1

服務器:SQL 2008 R2;數據集:50-100萬之間記錄日期時間接近

我有一個全速情況下的表從我需要確定所有的汽車的平均時速的車輛(即一個號碼不是每輛車的數字)。訣竅是記錄的時間跨度很大的週期,沒有對時間沒有一致性時,其中記錄的記錄,所以我可能會在8點15分的車並沒有什麼再錄製,直到8點20分,而另一輛車可能有記錄在該時間段內每10秒鐘一次。

給定一個特定的日期和時間,我需要確定這個平均速度,並且由於它很有可能在給定的時間和該車的記錄之間不會直接匹配,所以我需要從記錄中選擇速度最接近給定的時間。

這裏是一個安裝腳本

CREATE TABLE [dbo].[SpeedRecords](
    [Id] [int] IDENTITY(1,1) NOT NULL, 
    [CarId] [int] NOT NULL, 
    [TimeOfEntry] [datetime] NOT NULL, 
    [Speed] [real] NOT NULL, 
CONSTRAINT [PK_SpeedRecords] PRIMARY KEY CLUSTERED ([Id] ASC)) 
go 
insert into SpeedRecords(CarId,TimeOfEntry,Speed) 
select 1, '11/22/2010 08:16:13', 67.56 union 
select 1, '11/22/2010 08:15:23', 63.87 union 
select 1, '11/22/2010 08:36:33', 45.66 union 
select 1, '11/22/2010 08:23:43', 56.87 union 
select 2, '11/22/2010 08:36:53', 78.66 union 
select 2, '11/22/2010 08:04:03', 34.88 union 
select 2, '11/22/2010 08:08:51', 23.23 union 
select 2, '11/22/2010 08:34:52', 65.87 union 
select 3, '11/22/2010 08:58:43', 45.34 union 
select 3, '11/22/2010 08:34:56', 73.23 union 
select 3, '11/22/2010 08:12:34', 12.87 union 
select 4, '11/22/2010 08:45:12', 66.45 union 
select 4, '11/22/2010 08:36:34', 90.87 union 
select 4, '11/22/2010 08:24:23', 34.89 union 
select 4, '11/22/2010 08:45:12', 45.83 


declare @dt datetime = '11/22/2010 08:43:14' 
-- select the average speed (for all cars) but 
-- only use the record for each car closest to 
-- the given datetime (@dt) 

回答

1

使用ABS(DATEDIFF ..)制定差異最小,訂單上,限制。

變化ROW_NUMBER() to DENSE_RANK(),如果你想在平均2個速度是從@dt

declare @dt datetime = '11/22/2010 08:43:14' 
-- select the average speed (for all cars) but 
-- only use the record for each car closest to 
-- the given datetime (@dt) 

;WITH Closest AS 
(
    SELECT 
     Speed, 
     ROW_NUMBER() OVER(PARTITION BY ID ORDER BY ABS(DATEDIFF(second,@dt,TimeOfEntry))) AS Ranking 
    FROM 
     SpeedRecords 

) 
SELECT 
    AVG(Speed) 
FROM 
    Closest 
WHERE 
    Ranking = 1 

對於SQL Server 2000你需要一個相關子查詢和頂部,但它會很尷尬一樣差的

相關問題