DELIMITER $$
CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`rateView`()
BEGIN
/**
 * Muestra información sobre tasas de cambio de Dolares
 */
	SELECT
			t.year año,
			t.month mes,
			pay.dollars dolares,
			pay.changePractical cambioPractico,
			CAST(SUM(iit.foreignValue ) / SUM(iit.taxableBase) AS DECIMAL(5,4))cambioTeorico,
			pay.changeOfficial cambioOficial
		FROM invoiceIn ii
			JOIN time t ON t.dated = ii.issued
			JOIN invoiceInTax iit ON ii.id = iit.invoiceInFk
			JOIN
			(	SELECT
						t.year,
						t.month,
						CAST(SUM(p.divisa) AS DECIMAL(10,2)) dollars,
						CAST(SUM(p.divisa) / SUM(p.amount) AS DECIMAL(5,4)) changePractical,
						CAST(rr.value * 0.998 AS DECIMAL(5,4)) changeOfficial
					FROM payment p
						JOIN time t ON t.dated = p.received
						JOIN referenceRate rr ON rr.dated = p.received
						JOIN currency c ON c.id = rr.currencyFk
					WHERE p.divisa
						AND c.code = 'USD'
					GROUP BY t.year, t.month
			) pay ON t.year = pay.year AND t.month = pay.month
			JOIN currency c ON c.id = ii.currencyFk
		WHERE c.code = 'USD'
			AND iit.foreignValue
			AND iit.taxableBase
		GROUP BY t.year, t.month;
END$$
DELIMITER ;
