SQL Server 中的两行值比较

时间:2021-01-07 15:25:57

标签: sql sql-server

在我的 SQL Server 表中,我两次处于“关闭”状态。我想删除第二条记录。

删除第二条记录的条件如下。

<块引用>

如果第一行 END_TIME 等于第二行 START_TIME,那么应该删除第二行。应该只选择第一行

请帮我解决这个问题。

参考附件截图

Image

2 个答案:

答案 0 :(得分:0)

也许您可以使用基于联接的删除,在该联接中,您可以在 end_time 和 start_time 列上将表与自身联接。

DELETE t2
FROM MyTable t1
INNER JOIN MyTable t2 on t1.END_TIME = t2.END_TIME
WHERE t1.STATUS = 'Closed'
AND t2.STATUS = 'Closed'

这将删除 STATUS = 'Closed' 的记录,该记录的开始时间与另一条记录的结束时间相同。如果我正确理解你的场景,这就是诀窍。但是您需要详细说明您的确切情况。并且可能添加一个仅在单个记录受到影响时提交的事务,因为具有开始时间的记录和具有相同结束时间的另一条记录可能并不总是相关的。

答案 1 :(得分:0)

下面一个完整的例子,包括表创建和行的插入和删除。 我也考虑过 start_time 等于 end_time 的情况。

create table [TABLE] (start_time int, status varchar(max), end_time int);
GO -- create the table
insert into [TABLE] values (1,'CLOSED', 2),(2,'CLOSED', 3);
GO -- insert two rows 1st end is 2nd start
delete from [TABLE] where status='CLOSED' and start_time in (select end_time from  [TABLE] where status='CLOSED' and start_time<>end_time) 
GO -- will delete the 2nd row
select * from [TABLE] 
GO -- show cleaned table
相关问题