DELIMITER $$
CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn2008`.`rateView`()
BEGIN

	SELECT 
			t.year as año,
			t.month as  mes, 
			pagos.dolares,
			pagos.cambioPractico,
			CAST(sum(divisa) / sum(bi) as DECIMAL(5,4)) as cambioTeorico,
			pagos.cambioOficial
		FROM recibida r
			JOIN time t ON t.date = r.fecha
			JOIN recibida_iva ri ON r.id = ri.recibida_id
			JOIN
			(	
				SELECT 
					t.year as Año,
					t.month as  Mes, 
					cast(sum(divisa) as DECIMAL(10,2)) as dolares,
					cast(sum(divisa) / sum(importe) as DECIMAL(5,4)) as cambioPractico,
					cast(rr.rate * 0.998 as DECIMAL(5,4)) as cambioOficial
				FROM pago p
				JOIN time t ON t.date = p.fecha
				JOIN reference_rate rr ON rr.date = p.fecha AND moneda_id = 2
				WHERE divisa 
				AND fecha >= '2015-01-11' 
				GROUP BY t.year, t.month
			) pagos ON t.year = pagos.Año AND t.month = pagos.Mes
		WHERE moneda_id = 2
			AND fecha >= '2015-01-01'
			AND divisa 
			AND bi
		GROUP BY t.year, t.month;

END$$
DELIMITER ;
