日期:2014-05-18  浏览次数:20502 次

问一个较为复杂的存储过程的写法
数据库的结构是这样的:

字段1:OBS_TIME(datetime)
字段2:VALUE(integer)

每5分钟会有1个值录入,也就是说一小时会有12个。

现在写一个存储过程,通过提供字段1(OBS_TIME)的上下限,返回以下数据:

OBS_TIME,VALUE,该小时12个VALUE的标准差。

关于标准差的介绍可以查看这里:


------解决方案--------------------
用STDEV ( expression )标准差的聚合函数

select stdev(value) from 表 where obc_time between '时间下限' and '时间上限'

------解决方案--------------------
两个值有点差别, 应该是我的语句很多地方按int运算引起的误差. 所谓失之毫粒,差之千里.
------解决方案--------------------
create table test(
OBS_TIME datetime,
VALUE int
)
--在指定时间内,每五分钟加一个值
create proc addData 
@start datetime,@end datetime,@value int
as
while datediff(mi,dateadd(mi,5,@start),@end)>=0
begin
insert into test values(@start,@value)
select @start = dateadd(mi,5,@start)
select @value = @value+3
continue
end

--得到指定时间间隔所有1个小时的标准差
create proc getStandard
@start datetime,@end datetime
--@start,@end分别为开始时间和结束时间,而且该存储过程只能得到间隔是1个小时标准差,间隔小于一个小时不算。
as
create table #standard(
value float
)
while datediff(hh,@start,@end)>=1
begin
insert into #standard
select stdev(value) from test where OBS_TIME between @start and dateadd(hh,1,@start)
select @start = dateadd(hh,1,@start)
continue
end
select * from #standard

可以得分不?