-- Costo y existencia en Kg por linea consolidado, al ultimo dia del mes
-- anterior

-- Parametro @DIA: fecha (historico) de la existencia, en formato YYYY-MM-DD

SET NAMES 'utf8';

SELECT
	RIGHT(l.id_linea,2) AS Product_Line_code,
       	l.descripcion AS Product_Line,
       	ROUND(SUM(e.costo_unidad * e.cantidad), 2) AS Stock_Avg_Cost,
	ROUND(SUM(e.cantidad * i.peso), 2) AS Stock_Kg

FROM
	existencia_historico e
	JOIN item i
       		USING ( id_item )
	JOIN linea l 
		ON ( l.id_linea = i.id_linea
			AND l.tipo = i.tipo )

WHERE
	(e.fecha = @DIA)

GROUP BY 
	l.id_linea

HAVING
	(Stock_Avg_Cost + Stock_Kg > 0)

ORDER BY
	Stock_Avg_Cost DESC

