-- Estadísticas anuales

SELECT YEAR(dv.fecha) AS Year,
	COUNT(DISTINCT(dv.id_documento)) AS Number_of_invoices,
	COUNT(DISTINCT(c.id_cliente)) AS Number_of_customers,
	COUNT(DISTINCT(z.id_depto)) AS Number_of_cities,
	SUM(dvi.valor) AS Net_Sales,
        ROUND(  
                SUM(dvi.cantidad * i.peso * (IF(dvi.valor>0,1,-1))), 4
        ) AS Weight_Kg

FROM documento_ventas dv
	JOIN documento_ventas_has_item dvi
		USING ( id_documento,id_sucursal )
	JOIN item i
		USING ( id_item )
	LEFT JOIN cliente c
		USING ( id_cliente )
	JOIN view_ciudades z
		ON (c.id_zona = z.id_ciudad)

WHERE (LEFT(dv.id_documento,2) = 'DV' OR
         LEFT(dv.id_documento,2) = 'EF' OR
         LEFT(dv.id_documento,1) = 'F')

GROUP BY Year
