1

我有一个包含以下列的单个位置的每日天气数据表(在 SQL Server 2005 中):

LogDate                 DATETIME  
HighTemp                INT  
Temp6MonthHighAverage   INT  

LogDateHighTemp有数据。HighTemp6MonthAverage顾名思义,将填充以 . 结尾的 6 个月的平均高温LogDate

对于跨越数十年的数据,LowTemp 以及湿度和其他几个项目也有类似的要求。

我发现自己在圈子里思考。我可以使用集合操作为 UPDATE 语句中的每一行得出这个平均值,还是需要使用游标实现解决方案?我将不胜感激任何建议。

4

3 回答 3

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
于 2012-08-27T04:25:16.570 回答
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 以在添加新日期时填补空白。

于 2012-08-27T04:18:08.120 回答
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
于 2012-08-27T04:12:48.040 回答