Median Funktion

\r\nCREATE DEFINER=`allapow`@`%` FUNCTION `weighting_median`(p_entry_id int(11), p_type varchar(10)) RETURNS float(6,3)\r\nBEGIN\r\n-- soll in Abfragen benutzt werden\r\n-- um den Median der Wichtungen pro Entry zu haben\r\nDECLARE v_median_val FLOAT(6,3);\r\nDECLARE v_tablename VARCHAR(50);\r\n\r\n\r\nif p_type = 'pro'\r\nthen\r\n	SELECT avg(t1.weighting) into v_median_val FROM (\r\n	SELECT @rownum:=@rownum+1 as `row_number`, wp.weighting\r\n	  FROM weighting_pro wp,  (SELECT @rownum:=0) r\r\n	  WHERE wp.entry_pro_id = p_entry_id\r\n	  -- put some where clause here\r\n	  ORDER BY wp.weighting\r\n	) as t1, \r\n	(\r\n	  SELECT count(*) as total_rows\r\n	  FROM weighting_pro\r\n	  WHERE entry_pro_id = p_entry_id\r\n	  -- put same where clause here\r\n	) as t2\r\n	WHERE 1\r\n	AND t1.row_number in ( floor((t2.total_rows+1)/2), floor((t2.total_rows+2)/2) );\r\nelseif p_type = 'contra'\r\nthen\r\n	SELECT avg(t1.weighting) into v_median_val FROM (\r\n	SELECT @rownum:=@rownum+1 as `row_number`, wc.weighting\r\n	  FROM weighting_contra wc,  (SELECT @rownum:=0) r\r\n	  WHERE wc.entry_contra_id = p_entry_id\r\n	  -- put some where clause here\r\n	  ORDER BY wc.weighting\r\n	) as t1, \r\n	(\r\n	  SELECT count(*) as total_rows\r\n	  FROM weighting_contra\r\n	  WHERE entry_contra_id = p_entry_id\r\n	  -- put same where clause here\r\n	) as t2\r\n	WHERE 1\r\n	AND t1.row_number in ( floor((t2.total_rows+1)/2), floor((t2.total_rows+2)/2) );\r\nelse\r\nset v_median_val = 1;\r\nend if;\r\nRETURN v_median_val;\r\nEND\r\n