我必须测试表中的序列并且必须删除错误的记录。例如:
DATE DriverId CodeId
2014/03/01 14:00:00, 7168, 22 -- GO
2014/03/01 14:30:00, 7168, 23 -- STOP
2014/03/01 14:40:00, 7168, 22 -- GO
2014/03/01 15:10:00, 7168, 22 -- GO <--- delete this record
2014/03/01 16:00:00, 7168, 23 -- STOP
当我删除了worng记录时,我必须计算GO&amp;之间的时间。停止
我正在使用SQL Server 2012
答案 0 :(得分:1)
假设日期具有序列顺序,似乎您要删除值与前一个值相同的那个:
with todelete as (
select t.*, lag(codeid) over (order by "date") as prev_codeid
from table t
)
delete from todelete
where prev_codeid = codeid;
这是SQL Server 2012语法。您可以在早期版本中使用相关子查询执行此操作:
with todelete as (
select t.*,
(select top 1 codeid
from table t2
where t2."date" < t."date"
order by t2.date desc
) as prev_codeid
from table t
)
delete from todelete
where prev_codeid = codeid;