DELIMITER $$
CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `bs`.`vivosMuertos`()
BEGIN
	
	/**
	 * Devuelve el número de clientes nuevos y muertos,
	 * dependiendo de la fecha actual.
	 *
	 * @param @datSTART Fecha de inicio a buscar
	 * @param @datEND Fecha de finalización a buscar
	 */

		SET @datSTART = TIMESTAMPADD(YEAR,-2,util.VN_CURDATE());
		SET @datEND = TIMESTAMPADD(DAY,-DAY(util.VN_CURDATE()),util.VN_CURDATE());
	
	DROP TEMPORARY TABLE IF EXISTS tmp.VivosMuertos;
	
	CREATE TEMPORARY TABLE tmp.VivosMuertos
		SELECT c.Id_Cliente, tm.yearMonth, f.Compra, 0 as Nuevo, 0 as Muerto
		FROM vn2008.Clientes c
			JOIN
				(SELECT DISTINCT yearMonth
				FROM vn2008.time
				WHERE date BETWEEN @datSTART
					AND @datEND ) tm
			LEFT JOIN
				(SELECT DISTINCT tm.yearMonth, f.Id_Cliente , 1 as Compra
					FROM vn2008.Facturas f
			        	JOIN vn2008.time tm ON tm.date = f.Fecha
					WHERE Fecha BETWEEN @datSTART
						AND @datEND) f ON f.yearMonth = tm.yearMonth
						AND f.Id_Cliente = c.Id_Cliente;
	
	UPDATE tmp.VivosMuertos vm
		JOIN
			(SELECT MIN(tm.yearMonth) firstMonth, f.Id_Cliente 
			FROM vn2008.Facturas f
		        JOIN vn2008.time tm ON tm.date = f.Fecha
			WHERE Fecha BETWEEN @datSTART AND @datEND
		    GROUP BY f.Id_Cliente ) fm ON fm.firstMonth = vm.yearMonth
		    	AND fm.Id_Cliente = vm.Id_Cliente

	SET Nuevo = 1;
	  
	SELECT max(yearMonth) INTO @lastYearMonth FROM tmp.VivosMuertos;
	 
	UPDATE tmp.VivosMuertos vm
	JOIN (
	  SELECT MAX(tm.yearMonth) firstMonth, f.Id_Cliente
			FROM vn2008.Facturas f
	        	JOIN vn2008.time tm ON tm.date = f.Fecha
			WHERE Fecha BETWEEN @datSTART AND @datEND
	        GROUP BY f.Id_Cliente ) fm ON fm.firstMonth = vm.yearMonth
				AND fm.Id_Cliente = vm.Id_Cliente

	SET Muerto = 1

	WHERE yearMonth < @lastYearMonth;

	SELECT * FROM tmp.VivosMuertos;

END$$
DELIMITER ;
