-- Ventas anuales por item por cliente
-- Incluye familia, sector, y linea de analisis de Directorio
-- Excluye traslados
-- Cambios solicitados en 2013-06-25: Zona y Suc2

SELECT
	dv.id_sucursal AS Branch,
	se.id_sector AS Id_Sector,
	se.descripcion AS Sector,
	cs.id_cliente AS Id_Client,
	cs.nombre_cliente AS Client,
	dv.id_vendedor AS Id_Salesrep,
	vdr.nombre_vendedor AS Salesrep,
	l.familia AS 'Type',
	i.id_item AS Cod_item,
	i.descripcion AS Item,
	l.linea_analisis AS Line1,
	l.id_linea_analisis AS Id_Line1,
	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,
	SUM(dvi.valor-dvi.costo) AS Gross_Margin,
	ROUND(
		SUM(dvi.cantidad*i.peso*(IF(dvi.valor>0, 1, -1)))/1000, 2
	) AS Sales_MT

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  )
	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 ( LEFT(i.id_linea,2) = l.id_linea )
	LEFT JOIN linea_has_subfamilia ls
		ON ( l.id_linea = ls.id_linea)
	LEFT JOIN solosector se
		ON ( LEFT(cs.id_sector,2) = se.id_sector )
	LEFT JOIN vendedor vdr
		ON ( dv.id_vendedor = vdr.id_vendedor
			AND dv.id_sucursal = vdr.id_sucursal)

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-10-31"

GROUP BY
	Branch,Id_Client,Cod_item,Id_Salesrep

ORDER BY
	Branch,Id_Client,Cod_item,Id_Salesrep
