-- Ventas por mes, item

SELECT 
	DATE_FORMAT(dv.fecha,"%Y-%m") AS Mes,
	i.id_item AS Codigo, 
	i.descripcion AS Item, 
	SUM(dvi.valor) AS Valor,
	COUNT(DISTINCT dv.id_documento) AS Num_facturas,
	SUM(dvi.cantidad) AS Cantidad,
	ROUND(SUM(dvi.cantidad*i.peso*(IF(dvi.valor>0, 1, -1))), 2) AS Peso_Kg,
	dv.id_sucursal AS Suc,
	i.unidad1 AS UoM 

FROM 
	documento_ventas dv 
	JOIN documento_ventas_has_item dvi 
		ON ( dv.id_documento=dvi.id_documento 
			AND dv.id_sucursal=dvi.id_sucursal ) 
	JOIN item i 
		ON ( dvi.id_item=i.id_item )

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

GROUP BY 
	Item,Mes,Suc

ORDER BY
	Suc,Item,Mes

