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

SELECT
	YEAR(dv.fecha) AS Year,
	cs.id_cliente AS Id_Client,
	cs.nombre_cliente AS Client,
	i.id_item AS Id_Item,
	i.descripcion AS Item,
	l.id_linea AS Id_Line,
	l.descripcion AS Line,
	ROUND(
		SUM(
			dvi.cantidad * i.peso * (IF(dvi.valor >0, 1 , -1))
		),
		2
	) AS Sales_Kg,
	SUM(dvi.valor) AS Sales_COP,
	SUM(dvi.costo) AS COGS,
	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 
			AND dvi.id_sucursal=i.id_sucursal )
	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 )

WHERE
    LEFT(dv.id_documento,2) RLIKE "F|D[^0-9MBPC]" 
    AND (i.tipo != "5")
    AND YEAR(dv.fecha) = 2013

GROUP BY
	Id_Client,Id_Item
HAVING
	Id_Client > 999
ORDER BY
	Id_Client,Id_Item
