SET NAMES 'utf8';

SELECT 
       	i.id_linea AS Sub_line,
	i.id_item AS Item,
	l.descripcion AS Product_line,
       	i.descripcion AS Description,
	su.nombre_sucursal AS Branch,
	CONCAT(EXTRACT(YEAR_MONTH FROM dv.fecha), '01') AS Month,
       	SUM(dvi.valor) AS Net_Sales, 
	ROUND(  
		SUM(dvi.cantidad * i.peso * (IF(dvi.valor>0,1,-1))), 4
	) AS Weight_Kg,
	SUM(
		dvi.cantidad * (IF(dvi.valor >0, 1 , -1))
	) AS Amount_UoM

FROM
	documento_ventas dv
	JOIN documento_ventas_has_item dvi 
		ON ( dv.id_documento = dvi.id_documento
			AND dv.id_sucursal = dvi.id_sucursal )
		LEFT JOIN sucursal su
				ON (dv.id_sucursal = su.id_sucursal )

	JOIN item i
		USING ( id_item )
	LEFT JOIN view_lineas l
		USING (id_linea)

WHERE
	YEAR(dv.fecha) >= 2017
	AND l.id_linea IN ('1542', '1548', '1554', '1557', '1560')

GROUP BY
	Item, Branch, Month
