Sqlserver
 sql >> Database >  >> RDS >> Sqlserver

query sql per la differenza tra la riga corrente e la riga precedente in base a datetime

In SQL Server 2012+, puoi utilizzare lag() . In SQL Server 2008, usa apply :

select t.*,
       coalesce(t.cumulativeValue - tprev.cumulativeValue, t.cumulativeValue) as diff
from t outer apply
     (select top 1 tprev.*
      from t tprev
      where tprev.siteId = t.siteId and tprev.readtime < t.readtime
      order by tprev.readtime desc
     ) tprev;