DELIMITER $$
CREATE OR REPLACE DEFINER=`vn`@`localhost` PROCEDURE `bs`.`campaignComparative`(vDateFrom DATE, vDateTo DATE)
BEGIN
	SELECT 
		workerName, 
		id, 
		name, 
		CAST(SUM(previousAmmount) AS DECIMAL(10, 0)) AS previousAmmount, 
		CAST(SUM(currentAmmount) AS DECIMAL(10, 0)) AS currentAmmount 
	FROM (
			(SELECT 
				 CONCAT(w.firstname, ' ', w.lastName) AS workerName,
				 c.id,
				 c.name,
				 SUM(v.importe) AS previousAmmount,
				 0 currentAmmount
			FROM bs.ventas v
				INNER JOIN vn.`client` c ON v.Id_Cliente = c.id
				INNER JOIN vn.worker w ON c.salesPersonFk = w.id
			WHERE v.fecha BETWEEN DATE_ADD(vDateFrom, INTERVAL - 1 YEAR) 
				AND DATE_ADD(vDateTo, INTERVAL - 1 YEAR)
				GROUP BY w.id, v.Id_Cliente)
			UNION ALL
			(SELECT 
				 CONCAT(w.firstname, ' ', w.lastName) AS workerName,
				 c.id,
				 c.name,
				 0 AS previousAmmount,
				 SUM(s.quantity * s.price) AS currentAmmount
			FROM vn.sale s
				JOIN vn.ticket t ON t.id = s.ticketFk
				JOIN vn.client c ON c.id = t.clientFk
				JOIN vn.worker w ON c.salesPersonFk = w.id
			WHERE t.shipped BETWEEN vDateFrom
				AND vDateTo
				GROUP BY w.id, c.id)
			) comparative
		GROUP BY workerName, id
		HAVING (previousAmmount <> 0 OR currentAmmount <> 0)
		ORDER BY workerName, id;
END$$
DELIMITER ;
