如果first row's code column
等于 second rows number column
且second rows' code column
等于 first row's number column
,如何删除行
sql不能使用循环
将其用作示例代码
CREATE TABLE #temp(id int, code int, Number int)
Insert into #temp values(1,2,1)
Insert into #temp values(2,1,2)
Insert into #temp values(3,2,3)
Insert into #temp values(4,2,3)
Insert into #temp values(5,2,3)
select * from #temp
答案 0 :(得分:1)
因为您没有指定您正在使用的RDBMS。我假设它是SQL Server,那么你可以这样做:
;WITH CTE
AS
(
select * , ROW_NUMBER() OVER(ORDER BY ID) rownum
from temp
), RowsToDelete
AS(
SELECT c1.*
FROM CTE c1
INNER JOIN CTE c2 ON c1.rownum - c2.rownum = 1 AND c1.number = c2.code
)
DELETE r
FROM temp r
WHERE ID IN ( SELECT ID
FROM RowsToDelete);
对于样本数据,您发布的这将只删除一行,即:
ID CODE NUMBER
2 1 2
答案 1 :(得分:0)
只需使用连接即可使用您指定的条件获取要删除的行:
delete t1
from #temp t1
inner join #temp t2
on t1.code = t2.Number and t2.code = t1.Number
答案 2 :(得分:0)
删除t1
来自#temp t1
存在(
从#temp t2
中选择*其中t1.code = t2.Number和t2.code = t1.Number和t2.Id> t1.Id
)