-2

I need to subtract (cantidad 1 - cantidad 0) (cantidad 2 - 1 cantidad) (cantidad 3 - cantidad 2) for each line (that is my key field).

My SQL:

SELECT linea, producto, cantidad, operario, fecha 
FROM registro_cantidad_producida

Current Result:

enter image description here

Expected Result:

enter image description here

The Impaler
  • 38,638
  • 7
  • 30
  • 65

1 Answers1

0

You can use a correlated subquery to calculate the previous result:

select t.*,
       coalesce( t.cantid -
                 (select t2.cantid
                  from t t2
                  where t2.linea = t.linea and t2.fecha < t2.fecha
                  order by t2.fecha desc
                  limit 1
                 ),
                 t.cantid
                )
from t;
Gordon Linoff
  • 1,198,228
  • 53
  • 572
  • 709