V SQL Server 2012+ můžete použít lag()
. V SQL Server 2008 použijte 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;