DELIMITER $$
CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `bi`.`defaultersFromDate`(IN vDate DATE)
BEGIN

	SELECT t1.*, c.Cliente, w.code AS workerCode, c.pay_met_id,c.Vencimiento
	FROM (
	-- Filtramos aquellos clientes cuyo saldo se ha incrementado de ayer a hoy
		select * from(
			select today.client, today.amount todayAmount, yesterday.amount yesterdayAmount, round(yesterday.amount - today.amount,2) as difference, defaulterSince
			from
				(select client, amount, defaulterSince
				from defaulters
				where date = vDate and hasChanged) today
					join
				(select client, amount
				from defaulters
				where date = TIMESTAMPADD(DAY,-1,vDate)) yesterday using(client)

					having today.amount > 0 and difference <> 0
					) newDefaulters
	)t1 left join vn2008.Clientes c ON t1.client = c.Id_Cliente
		left join vn.worker w ON w.id = c.Id_Trabajador;
END$$
DELIMITER ;
