-- Ventas mensuales por item por documento cliente
-- Incluye familia, sector, linea, origen y destino

SELECT
	dv.id_sucursal AS Sucursal,
	dvi.id_bodega AS Bodega_origen,
	cs.id_cliente AS Id_Client,
	cs.nombre_cliente AS Client,
	ciu.nombre_ciudad AS Ciudad,
	ciu.nombre_depto AS Depto,
	dv.fecha AS Fecha,
	dv.id_documento AS Documento,
	dvi.id_item AS Cod_item,
	i.descripcion AS Item,
	l.linea_analisis AS Line1,
	ROUND(
		SUM(
			dvi.cantidad * i.peso * (IF(dvi.valor > 0, 1 , -1))
		),
		2
	) AS Sales_Kg,
	SUM(dvi.valor) AS Sales_COP

FROM
	documento_ventas dv
	JOIN documento_ventas_has_item dvi
		ON ( dv.id_documento=dvi.id_documento 
			AND dv.id_sucursal=dvi.id_sucursal )
	LEFT JOIN item i
		ON ( dvi.id_item=i.id_item  )
	LEFT JOIN cliente_has_sucursal cs
		ON ( dv.id_sucursal=cs.id_sucursal 
			AND dv.id_cliente=cs.id_cliente )
        LEFT JOIN view_lineas l
		ON ( i.id_linea = l.id_linea )
	LEFT JOIN view_ciudades ciu
		ON (ciu.id_ciudad = cs.ciudad)

WHERE
        (LEFT(dv.id_documento,2) = 'DV' OR
	 LEFT(dv.id_documento,2) = 'EF' OR
	 LEFT(dv.id_documento,1) = 'F')
	AND dv.fecha >= "2016-01-01"
	AND dv.fecha <= "2016-12-31"

GROUP BY
	Sucursal, Documento, Cod_item

