-- Ventas por mes por item de las lineas de tuberia

SET NAMES 'utf8';

SELECT 
	CONCAT(EXTRACT(YEAR_MONTH FROM dv.fecha), '01') AS Mes,
	s.nombre_sucursal AS Sucursal,
	l.descripcion AS Product_line,
	i.id_item AS Item,
       	i.descripcion AS Description,
       	SUM(dvi.valor) AS Net_Sales, 
	ROUND(
		SUM(
			dvi.cantidad * i.peso * (IF(dvi.valor >0, 1 , -1))
		),
		2
	) AS Amount_Kg,
	SUM(
		dvi.cantidad * (IF(dvi.valor >0, 1 , -1))
	) AS Amount_UoM,
       	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 )
	LEFT JOIN sucursal s
		ON (dv.id_sucursal = s.id_sucursal )
	JOIN item i
		USING ( id_item )
	LEFT JOIN view_lineas l
		USING ( id_linea )

WHERE
	YEAR(dv.fecha) >= 2020
	AND i.id_linea IN ('1548', '1560', '1554')

GROUP BY
	Mes, Sucursal, Item

ORDER BY
	Mes, Sucursal, Item
