En SQL Server 2012+, puede usar lag()
. En SQL Server 2008, use 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;