I’m trying to come up with a way to use a relative stdev range function in SQL Server 2005/8 without any looping. Assuming a test dataset (test_data) with 10 records and columns:
column_id identity(1,1), column_data, column_stdev
I would need my stdev() to work as follows:
stdev(column_data where id between i and i + 3) with i = column_id, autoincrementing.
So far I’m only able to acoomplish it via the following query, which is extra slow:
declare @i int
set @i=1
while @i < 11
begin
update test_data
set column_stdev = (select stdev(column_data) from test_data
where column_id between @i and @i+2)
set @i=@i+1
end
Could you, please, let me know if there is a way to avoid looping in order to set column_stdev to get stdev of the past 3 records in column_data.
One obvious improvement would be to get rid of the
WHILEloop and the row by row processing. If you are not doing it in an explicit transaction you will need to wait for 10 individual commits to complete and the total amount of work required is greater anyway as shown by the stats below.NB: I’m not claiming that my query can’t be improved upon however. You may be able to adjust the “quirky update” approach for your needs and do it with a single scan through the data for example.