I want to create a function that returns the median of a field. I'm working with sql 2000. I wrote:
create function mediana
(@tabla, @campo)
returns int
as
begin
declare @Median integer
return @Median =
(
(SELECT MAX(@campo) FROM
(SELECT TOP 50 PERCENT dia
FROM @tabla
ORDER BY @campo) AS t
)
+ (SELECT MIN(@campo) FROM
(SELECT TOP 50 PERCENT @campo
FROM @tabla ORDER BY @campo DESC) AS b
)
) / 2.0 ;
But I get many errors. How can I solve that, also I would like to apply this function to data grouped by other fiels. Would this be possible with this code?
ps: I've never created a function in sql before.
thanks