Если я правильно понимаю, вы хотите сохранить все записи с col2 = -1 и записи с ближайшим col1 к записям с -1.Если предположить, что в столбце col1 нет дубликатов, я бы сделал что-то вроде этого
delete from table where not col1 in
(
(select col1 from table where col2 = -1)
union
(select (select max(t2.col1) from table t2 where t2.col1 < t1.col1) from table t1 where t1.col2 = -1)
union
(select (select min(t4.col1) from table t4 where t4.col1 > t3.col1) from table t3 where t3.col2 = -1)
)
Изменить:
t4.col1 < t3.col1
должно быть t4.col1 > t3.col1
Я создал тестовую таблицу с col1и col2, оба типа int, col1 - это PK, но не автонумера
SELECT * from adjacent
Дает
col1 col2
1 5
3 4
4 2
7 -1
11 8
12 2
С указанными выше подвыборками:
SELECT * from adjacent
where
col1 in
(
(select col1 from adjacent where col2 = -1)
union
(select (select max(t2.col1) from adjacent t2 where t2.col1 < t1.col1) from adjacent t1 where t1.col2 = -1)
union
(select (select min(t4.col1) from adjacent t4 where t4.col1 > t3.col1) from adjacent t3 where t3.col2 = -1)
)
дает
col1 col2
4 2
7 -1
11 8
С not
также
SELECT * from adjacent
where
col1 not in
(
(select col1 from adjacent where col2 = -1)
union
(select (select max(t2.col1) from adjacent t2 where t2.col1 < t1.col1) from adjacent t1 where t1.col2 = -1)
union
(select (select min(t4.col1) from adjacent t4 where t4.col1 > t3.col1) from adjacent t3 where t3.col2 = -1)
)
дает
col1 col2
1 5
3 4
12 2
Наконец, удаление и выберите
delete from adjacent
where
col1 not in
(
(select col1 from adjacent where col2 = -1)
union
(select (select max(t2.col1) from adjacent t2 where t2.col1 < t1.col1) from adjacent t1 where t1.col2 = -1)
union
(select (select min(t4.col1) from adjacent t4 where t4.col1 > t3.col1) from adjacent t3 where t3.col2 = -1)
)
select * from adjacent
дает
col1 col2
4 2
7 -1
11 8