sql >> Base de Datos >  >> RDS >> Oracle

¿Cómo comparar valores para la última y la penúltima entrada en la tabla?

SELECT  *, value - nextvalue AS diff
FROM    (
        SELECT  m.*, LEAD(value) OVER (ORDER BY date DESC) AS nextvalue
        FROM    mytable m
        ORDER BY
                date DESC
        )
WHERE   rownum = 1

Actualización:

Para seleccionar resultados por empresa:

SELECT  value - nextvalue AS diff
FROM    (
        SELECT  m.*,
                LEAD(value) OVER (PARTITION BY companyId ORDER BY date DESC) AS nextvalue,
                ROW_NUMBER() OVER (PARTITION BY companyId ORDER BY date DESC) AS rn
        FROM    mytable m
        )
WHERE   rn = 1