Dear Colleagues. A query is required in the following way.
My question is how I would have to perform the select to generate the balance field. Thanks for your help.
Greetings
If you want to do it in a single query, you need to use auxiliary variables. Here an example, consider that you must execute the 3 sentences to obtain the desired result:
SET @TOTAL := 0;
SET @ARTICULO := '';
SELECT T.id, T.articulo, T.tipomov, T.cantidad, T.saldo
FROM (
SELECT id, articulo, tipomov, cantidad,
CASE
WHEN (@ARTICULO = '' OR @ARTICULO = articulo) AND tipomov = '01-INGRESO' THEN @TOTAL := @TOTAL + cantidad
WHEN (@ARTICULO = '' OR @ARTICULO = articulo) AND tipomov = '02-SALIDA' THEN @TOTAL := @TOTAL - cantidad
WHEN @ARTICULO != articulo AND tipomov = '01-INGRESO' THEN @TOTAL := 0 + cantidad
WHEN @ARTICULO != articulo AND tipomov = '02-SALIDA' THEN @TOTAL := 0 - cantidad
END AS saldo,
@ARTICULO := articulo
FROM kardex
ORDER BY articulo, id
) T;
excellent sql, but I think it can be reduced a bit. You can try the following:
SQL
we set a variable
SET @T:0;
We create sentence
SELECT articulo, tipomov, cantidad, IF(tipomov ='01-INGRESO',(@T:=@T+cantidad),(@T:=@T-cantidad)) AS saldo FROM kardex;