-- Sales per line per sector
SELECT 
	se.id_sector AS Sector_code,
	se.descripcion AS Sector,
	l.id_linea AS Product_Line_code,
       	l.descripcion AS Product_line,
       	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 linea l
		ON ( l.id_linea = LEFT( i.id_linea, 2 )
			AND l.tipo = i.tipo )
	JOIN cliente_has_sucursal cs
       		ON ( dv.id_sucursal = cs.id_sucursal 
			AND dv.id_cliente = cs.id_cliente )
	JOIN sector se
		ON ( se.id_sector = LEFT(cs.id_sector,2) )

WHERE
	LEFT( dv.id_documento, 2 ) RLIKE "F|D[^0-9MPBC]"
	AND NOT (i.tipo LIKE "5")
	AND NOT (dv.id_cliente LIKE "999")
	AND EXTRACT(YEAR_MONTH FROM dv.fecha) = @MES

GROUP BY
	se.id_sector,l.id_linea

ORDER BY
	Sector,Product_Line
