我的数据库中有一个名为“Value”的字段,我需要计算这个“值”的移动平均值。
该表有一个主键“index”,用作表的排序顺序。
在广泛的搜索中出现了几种解决此问题的方法,但我发现有些服务器具有特殊服务器UI的引用,以实现此目的。
ADS版本10.1 +中是否有这样的功能?
答案 0 :(得分:1)
我认为这是一个相当简单的自我加入。通过将表连接到自身,您可以设置连接条件,以便每个度量(行)连接到N个先前的度量,然后选择该值的平均值和逐行ID。
像这样:
create table T
(
id int identity(1,1) primary key,
value float
)
go
-- Insert some test data
declare @i int = 0
while @i < 1200
begin
-- something random + @i => rising trend
insert T values (@i + rand()*100);
set @i = @i + 1
end
-- Take a look at some of the data (optional)
-- Chaotic, but there is an upwards trend in the values.
select top 100 * from T
-- Fetch sliding average (over 20 measurements)
-- While it can fluctuate, the upwards tendency is now plain to see.
declare @duration int = 20
select
t1.id,
avg(t2.value) [Sliding average]
from
T T1
join T T2 on T2.id between T1.id - @duration and T1.id
where
t1.ID < 100
group by
t1.id
-- To see the basis for each average...
select
t1.id [Group number],
t2.id [Measurement ID],
t2.value [Value]
from
T T1
join T T2 on T2.id between T1.id - @duration and T1.id
where
t1.ID < 100
order by
t1.id, t2.id
这是你的想法吗?