Sum cumulatively in the same MYSQL query

2

I have the following query:

I need to add and subtract the entries and exits of units based on dates, where in the column BALANCE reflects the partial result but I have not achieved it correctly. Why:

As seen in the image in the first row the BALANCE MUST be 0 and then it is 300, then 650 and so on ...

Greetings, Thank you.

    
asked by sebamim 19.12.2018 в 17:05
source

1 answer

2

In the balance query you need to add one more condition. You must check that the date is not before the range you request.

The query would be something like this:

SELECT
    a.fecha,
    a.Documento,
    a.'Proveedor / Cliente',
    a.'Entrada / Salida Unidades'
    (
        SELECT
         sum(
            b.'Entrada / Salida Unidades'
        )
        FROM 
            v_movimiento_unidades_bodegas b
        WHERE
            a.cod_materia_prima = 'Audifonos'
            AND a.cod_bodega = 7
            AND b.Fecha <= a.Fecha
            AND b.Fecha >= '2018-10-18'          <---------- Condición que falta
    ) AS Saldo
    FROM 
        v_movimiento_unidades_bodegas AS a
    WHERE   
        a.cod_materia_prima = 'Audifonos'
        AND a.cod_bodega = 7
        AND a.Fecha BETWEEN '2018-10-18'
        AND '2018-12-19'
    
answered by 19.12.2018 / 17:15
source