Good afternoon, I have the following procedure
CREATE DEFINER=root@localhost PROCEDURE kardex(codigoproducto INT(5))
BEGIN
SET @canant=0.00,@totant=0.00,@preant=0.00;
SELECT
fecha
, numeroMovimiento
, IF(tipoMovi=1,detalle.cantidad,NULL) CantidadC
, IF(tipoMovi=1,detalle.precio,NULL) PrecioC
, IF(tipoMovi=1,detalle.cantidad * detalle.precio,NULL) TOTALC
, IF(tipoMovi=-1,detalle.cantidad,NULL) CantidadV
, IF(tipoMovi=-1,ROUND(@preant,6),NULL) PrecioV
, IF(tipoMovi=-1,detalle.cantidad * @preant,NULL) TOTALV
, IF(tipoMovi=1,@canant:=@canant+detalle.cantidad,@canant:=@canant - detalle.cantidad) CantidadT
, IF(tipoMovi=1,@totant:=ROUND(@totant+detalle.cantidad * detalle.precio,4),@totant:=ROUND(IF(@canant=0,0,@totant - detalle.cantidad * @preant),4)) TOTALT
,@preant:=@totant/@canant PrecioT
FROM
detallem
INNER JOIN movimiento
ON (detallem.numeroMovimiento = movimiento.numeroMovimiento)
INNER JOIN producto
ON (detallem.codproducto = producto.codproducto)
WHERE (producto.codproducto=codigoproducto);
END$$
It generates a result similar to this:
My question is how to get the value that is in red, try:
SELECT IFNULL(SUM(detalle.cantidad * detalle.precio)/SUM(detalle.cantidad),0.00) Precio FROM movimiento
INNER JOIN detalle ON movimiento.numeroMovimiento=detallem.numeroMovimiento WHERE tipoMovi=1 AND codproducto=3
Getting: 12.898401974
when it should be 12.931855103
Note: in the calculation of this kardex in the sale price the last total price will be taken. In the example sold 9000 could be sold at 1.00 as 99.00 but will still take the value of 12.895874 which is the last calculated value. THANK YOU