我有一个表(在SQL Server 2005中),包含这些列的单个位置的每日天气数据:
LogDate DATETIME
HighTemp INT
Temp6MonthHighAverage INT
LogDate
和HighTemp
有数据。顾名思义,HighTemp6MonthAverage
将填充以LogDate
结尾的6个月的平均高温。
对于数十年来的数据,LowTemp以及湿度和其他一些项目也有类似的要求。
我发现自己在圈子里思考。我可以使用set操作为UPDATE语句中的每一行派生此平均值,还是需要使用游标实现解决方案?我将不胜感激任何建议。
答案 0 :(得分:3)
-- select
select HighTemp, LogDate,(select AVG(HighTemp)
from tbl where
DATEDIFF(MONTH, LogDate, t1.LogDate) between 0 and 6)
from tbl t1
-- update
update t1 set Temp6MonthHighAverage = (select AVG(HighTemp)
from tbl where
DATEDIFF(MONTH, LogDate, t1.LogDate) between 0 and 6)
from tbl t1
答案 1 :(得分:1)
您当然可以通过简单的更新来完成此操作:
UPDATE table SET Temp6MonthHighAverage =
(SELECT AVG(HighTemp) FROM table t2 WHERE
t2.LogDate <= table.LogDate
AND t2.LogDate > DATEADD(m, -6, table.LogDate)
)
为避免不断重新计算(因为过去不会改变),只需在末尾添加WHERE Temp6MonthHighAverage IS NULL
,并根据需要运行相同的UPDATE,以便在添加新日期时填补空白。 / p>
答案 2 :(得分:0)
看看这样的事情
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