要使用标准 SQL 执行此操作,您可以使用相关子查询。这个想法是获取以前的值,并且只保留与当前值不同的行:
select a.*
from (select t.*
(select max(id) from t t2 where t2.id < t.id) as pevid
from t
) a left outer join
t aprev
on a.previd = aprev.id
where aprev.value <> a.value or aprev.value is null
This is really an implementation of the lag()
function, but without window functions.
You can also write this using top/limit/rownum and doing an order by in the subquery:
select a.*
from (select t.*
(select top 1 id from t t2 where t2.id < t.id order by id desc) as pevid
from t
) a left outer join
t aprev
on a.previd = aprev.id
where aprev.value <> a.value or aprev.value is null
This, in turn, can be simplified to remove the last join:
select a.*
from (select t.*
(select top 1 val from t t2 where t2.id < t.id order by id desc) as pevval
from t
)
where a.prevval <> a.value or a.prevval is null