I want to calculate the median of a column, assign that to a dynamic variable, and use that in further calculations. This is what I've written:
declare @sqlcmd nvarchar(max)
declare @tablename nvarchar(max)
set @tablename = 'table1'
-- calculate median
declare @median float
set @sqlcmd =
'SELECT
((SELECT MAX(field1) FROM
(SELECT TOP 50 PERCENT field1 FROM ' + @tablename + ' Where field1 is not null
ORDER BY field1) AS BottomHalf)
+
(SELECT MIN(field1) FROM
(SELECT TOP 50 PERCENT field1FROM ' + @tablename + ' Where field1 is not null
ORDER BY field1 DESC) AS TopHalf)
) / 2'
execute sp_executesql @sqlcmd
set @median = ???
-- calculate value2 as value 1 minus median
'update ' + @tablename +
' set value2 = value 1 - ' + @median
execute sp_executesql @sqlcmd
The result of my experimentation is either:
- "Error converting data type nvarchar to float."
- Or if I remove the second calculation, it simply pops up the result to the result window.
Using SQL Server 2012. Thank you in advance!