-- Sales per payment terms per customer/sector/branch year to year
-- For 5-Year presentation

SELECT
	YEAR(dv.fecha) AS Year,
        dv.id_sucursal AS Branch,
	z.nombre_depto AS Zone,
	se.descripcion AS Sector,
        COUNT(DISTINCT dv.id_cliente) AS Count_Customers,
	IF(
		(dv.fecha_vencimiento - dv.fecha) <= 5,
		'cash',
		'credit'
	) AS Sale_conditions,
        ROUND(  
                SUM(dvi.cantidad * i.peso * (IF(dvi.valor>0,1,-1))), 4
        ) AS Weight_Kg,
        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 )
	LEFT JOIN cliente c
		USING ( id_cliente )
	LEFT JOIN view_ciudades z
		ON ( c.id_zona = z.id_ciudad )
	LEFT JOIN sector se
		USING ( id_sector )

WHERE
        (LEFT(dv.id_documento,2) = 'DV' OR
         LEFT(dv.id_documento,2) = 'EF' OR
         LEFT(dv.id_documento,1) = 'F')
        AND NOT (dv.id_cliente LIKE "999")
        AND YEAR(dv.fecha) >= 2015
	
GROUP BY
	Year, Branch, Sale_conditions, Zone, Sector
