Hello allThe below code gets a number @var1 from tabel1 based on @stat. It then uses that number to calculate the avg and stdev for var1 days from col1 in tabel1. It returns @var1, avg, stdev and also the last observation (col1 from tbl2). DECLARE @stat varchar(64) SET @stat = 'stat1' DECLARE @var1 smallint SELECT @var1 = col1 FROM tabel1 WHERE stat = @stat SELECT TOP(@var1) col1 INTO #tbl1 FROM tabel1 WHERE stat = stat1 ORDER BY date DESC DECLARE @avg FLOAT, @stdev FLOAT SELECT @avg = AVG(col1) ,@stdev = STDEV(col1) FROM tbl1 SELECT TOP(1) col1 INTO #tbl2 FROM #tbl1 SELECT @var1 as name1 ,@avg as name2 ,@stdev as name3 ,col1 as name4 FROM #tbl2 DROP TABLE #tbl1, #tbl2
This works like it is supposed to, but it looks a bit messy with all those selects. Any ideas how to clean up the above while keeping it easy to read?I tried the following, but got the error:A SELECT statement that assigns a value to a variable must not be combined with data-retrieval operations. SELECT @var1 as name1 ,@avg = AVG(tbl1.col1) ,@stdev = STDEV(tbl1.col1) ,tbl2.col1 as name4 FROM #tbl1, #tbl2