看看这样的东西
DECLARE @Table TABLE(
LogDate DATETIME,
HighTemp INT,
Temp6MonthHighAverage INT
)
INSERT INTO @Table SELECT '01 Jan 2000', 15, NULL
INSERT INTO @Table SELECT '01 May 2000', 14, NULL
INSERT INTO @Table SELECT '01 Jun 2000', 13, NULL
INSERT INTO @Table SELECT '01 Jul 2000', 12, NULL
INSERT INTO @Table SELECT '01 Dec 2000', 17, NULL
SELECT *
FROM @Table
;WITH DistinctDates AS (
SELECT DATEADD(month,-6,LogDate) StartDate,
LogDate EndDate,
HighTemp
FROM @Table
)
, Aggregates AS (
SELECT dd.EndDate LogDate,
dd.HighTemp,
MAX(t.HighTemp) Temp6MonthHighAverage
FROM DistinctDates dd LEFT JOIN
@Table t ON t.LogDate BETWEEN dd.StartDate AND dd.EndDate
GROUP BY dd.EndDate,
dd.HighTemp
)
UPDATE @Table
SET Temp6MonthHighAverage = a.Temp6MonthHighAverage
FROM @Table t INNER JOIN
Aggregates a ON t.LogDate = a.LogDate
SELECT *
FROM @Table