I SQL Server 2012+ kan du använda lag()
. I SQL Server 2008 använder du 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;