服务器:sql 2008 R2;数据集:介于50到1亿之间的记录
我有一个充满车辆速度实例的表格,我需要确定所有车辆的平均速度(即一个数字而不是每辆车的数字)。诀窍是记录跨越了很长一段时间,并且记录记录的时间没有一致性,因此我可能在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)
答案 0 :(得分:1)
使用ABS(DATEDIFF ..)来计算最小差异,ORDER,限制。
如果您希望2个速度的平均值与@dt相同,则更改ROW_NUMBER() to DENSE_RANK()
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,你需要一个相关的子查询和TOP但它很尴尬