Oracle
 sql >> Database >  >> RDS >> Oracle

Come confrontare i valori per l'ultima e la penultima voce nella tabella?

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

Aggiornamento:

Per selezionare i risultati per azienda:

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