Good hope you can help me, I have two tables with the following information:
(Client Table)
clienteid nombre direccion telefono email
--------- ------- --------- -------- --------
001 gallo
002 salcedo
003 paul
41422102 sistema
(Movement Table)
movimientoid fecha cuentaid clienteid monto tipo descripcion
------------ ---------- -------- --------- -------- ------ -------------------
1 2018-11-01 CAJA-001 41422102 10000.00 1 Saldo Inicial
2 2018-11-01 CAJA-001 003 5000.00 -1 Compra Al Contado
3 2018-11-01 CAJA-001 003 100.00 -1 Compra Al Contado
4 2018-11-01 CAJA-001 41422102 100.00 -1 Compra Al Contado
I make a query with the movements table and it returns the ordered results:
SET @dispo=0;
SELECT movimientoId, DATE_FORMAT(fecha, '%d/%m/%y') fecha, descripcion,
IF(tipo=1, monto, NULL) deposito, IF(tipo=-1, monto, NULL) retiro,
IF(tipo=1,@dispo:=@dispo + monto,@dispo:=@dispo - monto) disponible FROM movimiento
WHERE movimiento.cuentaid='CAJA-001' AND movimiento.fecha BETWEEN '2018-11-01' AND '2018-11-01';
movimientoId fecha descripcion deposito retiro disponible
------------ -------- ----------------- -------- ------- ------------
1 01/11/18 Saldo Inicial 10000.00 (NULL) 10000.00
2 01/11/18 Compra Al Contado (NULL) 5000.00 5000.00
3 01/11/18 Compra Al Contado (NULL) 100.00 4900.00
4 01/11/18 Compra Al Contado (NULL) 100.00 4800.00
Now I want to include the name of the client, but this is where the query returns disordered records:
SET @dispo=0;
SELECT movimientoId, DATE_FORMAT(fecha, '%d/%m/%y') fecha, descripcion, nombre,
IF(tipo=1, monto, NULL) deposito, IF(tipo=-1, monto, NULL) retiro,
IF(tipo=1,@dispo:=@dispo + monto,@dispo:=@dispo - monto) disponible
FROM movimiento INNER JOIN cliente ON movimiento.clienteid=cliente.clienteid
WHERE movimiento.cuentaid='CAJA-001' AND movimiento.fecha BETWEEN '2018-11-01' AND '2018-11-01';
movimientoId fecha descripcion nombre deposito retiro disponible
------------ -------- ----------------- ------- -------- ------- ------------
2 01/11/18 Compra Al Contado paul (NULL) 5000.00 -5000.00
3 01/11/18 Compra Al Contado paul (NULL) 100.00 -5100.00
1 01/11/18 Saldo Inicial sistema 10000.00 (NULL) 4900.00
4 01/11/18 Compra Al Contado sistema (NULL) 100.00 4800.00
Messy for the column MovimientoId
or at least that I thought, since I could see that the records were sorted according to the PK
of the client table clienteId
. I already explained that the ordering of records by default depends on the engine, I did it with ORDER BY movimientoId
and if it comes out in order but the results of the column depósito
, retiro
and disponible
are calculated wrong. What form can my query be? Thanks.