Although I tested this only in sql server 2005 (since I don't have an instance of 2000), after replacing @t with a real table, it should still work on this platform.
select k, seq, val from ( select k, seq, val, (select top 1 val from @t aux where aux.k = main.k and aux.seq < main.seq order by seq desc) as prev_val, (select top 1 val from @t aux where aux.k = main.k and aux.seq > main.seq order by seq asc) as next_val from @t main ) x where prev_val = next_val
If you have an index on k, seq , performance should not be too bad, since correlated subqueries are a simple index scan.
Unfortunately, I don’t think lag and lead support in the SQL Server roadmap.
[In case someone is interested, I mean that in some databases you can write:
select key, seq, val from ( select key, seq, val, lag(val) over(partition by key order by seq) as prev_val, lead(val) over(partition by key order by seq) as next_val from t ) x where prev_val = next_val;
This would definitely come to your senses if you wanted to look at the previous two or more values, because you can write lag(val, 2) to look 2 lines back, etc. Finding directly the previous or next value is a simpler case where select top 1 ... does a great job. ]
source share