-- Evolucion de precio de venta (COP/Kg) por linea dia a dia para un rango 
-- de fechas

SELECT
	dv.fecha AS Date,
	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.valor-dvi.costo) AS Gross_Margin
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 )
        LEFT JOIN view_lineas l
		ON ( LEFT(i.id_linea,2) = l.id_linea )
	
WHERE
	LEFT(dv.id_documento,1) = "F"
	AND (i.tipo != "5")
	AND (dv.id_cliente != "999")
	AND dv.fecha >= "2013-01-01"
	AND dv.fecha <= "2014-01-31"
GROUP BY
	Date,Line
ORDER BY
	Date,Line
