-- Sales per payment terms year to year
-- For 5-Year presentation

SELECT
	YEAR(dv.fecha) AS Year,
        COUNT(DISTINCT dv.id_cliente) AS Count_Customers,
        COUNT(DISTINCT dv.id_documento) AS Count_Invoices,
	IF(
		(dv.fecha_vencimiento - dv.fecha) <= 5,
		'cash',
		'credit'
	) AS Sale_conditions,
        ROUND(  
                SUM(dvi.cantidad*i.peso*(IF(dvi.valor>0, 1, -1)))/1000, 2
        ) AS Weight_MT,
        SUM(dvi.valor) AS Value
FROM
        documento_ventas dv
        JOIN documento_ventas_has_item dvi
                USING ( id_documento,id_sucursal )
	LEFT JOIN item i
		USING ( id_item )

WHERE
	(LEFT(dv.id_documento,2) = 'DV' OR
	 LEFT(dv.id_documento,2) = 'EF' OR
	 LEFT(dv.id_documento,2) = 'CF' OR
	 LEFT(dv.id_documento,2) = 'EI' OR
	 LEFT(dv.id_documento,2) = 'AI' OR
	 LEFT(dv.id_documento,1) = 'F')
        AND YEAR(dv.fecha) >= 2018
	
GROUP BY
	Year, Sale_conditions
