Median Funktion

CREATE FUNCTION `weighting_median`(p_entry_id int(11), p_type varchar(10)) RETURNS float(6,3)
BEGIN
-- soll in Abfragen benutzt werden
-- um den Median der Wichtungen pro Entry zu haben
DECLARE v_median_val FLOAT(6,3);
DECLARE v_tablename VARCHAR(50);


if p_type = 'pro'
then
	SELECT avg(t1.weighting) into v_median_val FROM (
	SELECT @rownum:=@rownum+1 as `row_number`, wp.weighting
	  FROM weighting_pro wp,  (SELECT @rownum:=0) r
	  WHERE wp.entry_pro_id = p_entry_id
	  -- put some where clause here
	  ORDER BY wp.weighting
	) as t1, 
	(
	  SELECT count(*) as total_rows
	  FROM weighting_pro
	  WHERE entry_pro_id = p_entry_id
	  -- put same where clause here
	) as t2
	WHERE 1
	AND t1.row_number in ( floor((t2.total_rows+1)/2), floor((t2.total_rows+2)/2) );
elseif p_type = 'contra'
then
	SELECT avg(t1.weighting) into v_median_val FROM (
	SELECT @rownum:=@rownum+1 as `row_number`, wc.weighting
	  FROM weighting_contra wc,  (SELECT @rownum:=0) r
	  WHERE wc.entry_contra_id = p_entry_id
	  -- put some where clause here
	  ORDER BY wc.weighting
	) as t1, 
	(
	  SELECT count(*) as total_rows
	  FROM weighting_contra
	  WHERE entry_contra_id = p_entry_id
	  -- put same where clause here
	) as t2
	WHERE 1
	AND t1.row_number in ( floor((t2.total_rows+1)/2), floor((t2.total_rows+2)/2) );
else
set v_median_val = 1;
end if;
RETURN v_median_val;
END