-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
  • 45,731
  • 9
  • 39
  • 76

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,242,037
  • 58
  • 646
  • 786