我一直在尝试计算sql server中的移动平均值超过60个值,但我没有成功,希望你们帮帮我。
请查看以下数据
User startdate Enddate minutes moving average
Sync 3/15/2014 10:00 3/15/2014 11:47 107 113.4117647
Sync 3/15/2014 12:00 3/15/2014 13:45 105 112.8627451
Sync 3/15/2014 14:00 3/15/2014 15:41 101 112.5490196
Sync 3/15/2014 16:00 3/15/2014 17:12 72 112.372549
Sync 3/16/2014 1:00 3/16/2014 1:00 0 112.372549
Sync 3/16/2014 2:00 3/16/2014 2:00 0 112.372549
要求查询不得考虑零的行,即使它应该在表中显示,上面的最后一列除了平均值。
答案 0 :(得分:0)
试试这个。我不确定你是如何获得你在网格中放置的那些移动平均值,而我假设它们是由于之前没有显示的值。
DECLARE @table TABLE (
[User] NVARCHAR(10),
[StartDate] DATETIME,
[EndDate] DATETIME,
[Minutes] FLOAT,
[Average] FLOAT
)
INSERT INTO @table ([User],[startdate],[Enddate],[minutes]) VALUES
('Sync','3/15/2014 10:00','3/15/2014 11:47',107.0),
('Sync','3/15/2014 12:00','3/15/2014 13:45',105.0),
('Sync','3/15/2014 14:00','3/15/2014 15:41',101.0),
('Sync','3/15/2014 16:00','3/15/2014 17:12',72.0),
('Sync','3/16/2014 1:00','3/16/2014 1:00',0.0),
('Sync','3/16/2014 2:00','3/16/2014 2:00 ',0.0)
UPDATE t
SET [Average] = [avg]
FROM @table t
INNER JOIN (
SELECT
[startdate],
AVG(NULLIF([Minutes],0)) OVER (PARTITION BY [User] ORDER BY [startdate]) [avg]
FROM
@table
) a ON a.StartDate = t.StartDate
SELECT * FROM @table
让我知道你是怎么过的。
斯图尔特