DELIMITER $$
CREATE OR REPLACE DEFINER=`root`@`localhost` FUNCTION `vn`.`intrastat_estimateNet`(vIntrastat INT, vUnidades INT)
	RETURNS double
	DETERMINISTIC
BEGIN

	DECLARE vNet DOUBLE;

	SELECT ROUND(vUnidades / (SUM(media) / COUNT(media)), 2) INTO vNet
		FROM (SELECT *, unidades / neto media
				FROM vn2008.intrastat_data
				WHERE intrastat_id = vIntrastat
					AND neto
					AND unidades > 0
				ORDER BY odbc_date DESC
				LIMIT 20) t;

	RETURN vNet/2;

END$$
DELIMITER ;