-- Costo y existencia consolidados por item, al ultimo dia del mes anterior

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

SET NAMES 'utf8';

SELECT
	f.subfamilia AS Family,
	l.id_linea AS Line,
       	i.id_linea AS Sub_line,
	i.id_item AS Item,
       	i.descripcion AS Description,
       	ROUND(SUM(e.cantidad * e.costo_unidad), 2) AS Stock_Avg_Cost,
       	SUM(e.cantidad) AS Stock_UoM,
	ROUND(SUM(e.cantidad * i.peso), 2) AS Stock_Kg

FROM
	existencia_historico e
	JOIN item i
       		USING ( id_item )
	LEFT JOIN view_lineas l
		ON ( l.id_linea = LEFT( i.id_linea, 2 ) )
	LEFT JOIN linea_has_subfamilia f
		ON ( l.id_linea = f.id_linea )

WHERE
	(e.fecha = @DIA)

GROUP BY 
	i.id_item

HAVING
	(Stock_Avg_Cost + Stock_Kg > 0)

ORDER BY
	Stock_Avg_Cost DESC

