我有 40 个如下所示的表,每个表包含 3000 万条记录。
表RawData
:PK( CaregoryID
, Time
)
CategoryID Time IsSampled Value
-----------------------------------------------------------
1 2012-07-01 00:00:00.000 0 -> 1 65.36347
1 2012-07-01 00:00:11.000 0 80.16729
1 2012-07-01 00:00:14.000 0 29.19716
1 2012-07-01 00:00:25.000 0 -> 1 7.05847
1 2012-07-01 00:00:36.000 0 -> 1 98.08257
1 2012-07-01 00:00:57.000 0 75.35524
1 2012-07-01 00:00:59.000 0 35.35524
截至目前,IsSampled
所有记录的列均为 0。
我需要更新记录,以便对于每个 CategoryID 和每个分钟范围,具有 Max(Value)、Min(Value) 和第一条记录的记录应该为 1 IsSampled
。
以下是我创建的程序查询,但运行时间太长。(每桌约 2h 30m)
DECLARE @startRange datetime
DECLARE @endRange datetime
DECLARE @endTime datetime
SET @startRange = '2012-07-01 00:00:00.000'
SET @endTime = '2012-08-01 00:00:00.000'
WHILE (@startRange < @endTime)
BEGIN
SET @endRange = DATEADD(MI, 1, @startRange)
UPDATE r1
SET IsSampled = 1
FROM RawData AS r1
JOIN
(
SELECT r2.CategoryID,
MAX(Value) as MaxValue,
MIN(Value) as MinValue,
MIN([Time]) AS FirstTime
FROM RawData AS r2
WHERE @startRange <= [Time] AND [Time] < @endRange
GROUP BY CategoryID
) as samples
ON r1.CategoryID = samples.CategoryID
AND (r1.Value = samples.MaxValue
OR r1.Value = samples.MinValue
OR r1.[Time] = samples.FirstTime)
AND @startRange <= r1.[Time] AND r1.[Time] < @endRange
SET @startRange = DATEADD(MI, 1, @startRange)
END
有没有办法更快地更新这些表(大概以非程序方式)?谢谢!