SELECT 
	l.id_linea_analisis AS CodLinea1,
	l.linea_analisis AS Linea1,
       	SUM(dvi.valor) AS Net_Sales, 
	ROUND(
		SUM(
			dvi.cantidad * i.peso * (IF(dvi.valor >0, 1 , -1))
		),
		2
	) AS Amount_Kg,
       	SUM(dvi.costo) AS Cost_of_goods_sold

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 view_lineas l
		ON ( l.id_linea = LEFT( i.id_linea, 2 ) )

WHERE
	LEFT( dv.id_documento, 2 ) RLIKE "C|E|F|D[^0-9MPBC]"
	AND NOT (dv.id_cliente LIKE "999")
	AND YEAR(dv.fecha) = 2013

GROUP BY
	l.id_linea_analisis

ORDER BY
	Amount_Kg DESC
