Sql 从a=b和b=a的表中删除记录
我有一个有两个字段的表,a和b。有些记录在a=b和b=a的意义上是重复的。我想删除其中一条记录 考虑这一点:Sql 从a=b和b=a的表中删除记录,sql,sql-server,sql-delete,Sql,Sql Server,Sql Delete,我有一个有两个字段的表,a和b。有些记录在a=b和b=a的意义上是重复的。我想删除其中一条记录 考虑这一点: declare @temp table (a int, b int) insert into @temp values (1, 2) insert into @temp values (3, 4) insert into @temp values (4, 3) insert into @temp values (5, 6) --delete 3, 4 or 4, 3 select
declare @temp table (a int, b int)
insert into @temp values (1, 2)
insert into @temp values (3, 4)
insert into @temp values (4, 3)
insert into @temp values (5, 6)
--delete 3, 4 or 4, 3
select * from @temp
/*
a | b
--|--
1 | 2
3 | 4
5 | 6
or (I don't care which one)
a | b
--|--
1 | 2
4 | 3
5 | 6
*/
我怎样才能做到这一点?它需要支持Microsoft SQL Server 2000及更高版本
DELETE x
FROM TableName x
INNER JOIN
(
SELECT a.A, a.B
FROM tableName a
INNER JOIN tableName b
ON ((a.A = b.A AND a.b = b.b) OR
(a.A = b.B AND a.b = b.A)) AND
a.a > b.a
) y ON x.A = y.A AND x.B = y.B
declare @temp table (a int, b int)
insert into @temp values (1, 2)
insert into @temp values (3, 4)
insert into @temp values (4, 3)
insert into @temp values (5, 6)
insert into @temp values (6, 5)
--delete 3, 4 or 4, 3
delete t3
--select *
from
(select t1.a, t1.b,rank() over (partition by t2.a +t2.b order by t1.a) as row_number from @temp t1
join @temp t2 on t2.a = t1.b and t2.b = t1.a)c
join @temp t3 on c.a =t3.a and c.b = t3.b
where c.row_number <>1
select * from @temp
declare@temp表(a int,b int)
插入@temp值(1,2)
插入@temp值(3,4)
插入@temp值(4,3)
插入@temp值(5,6)
插入@temp值(6,5)
--删除3、4或4、3
删除t3
--选择*
从…起
(选择t1.a、t1.b、rank()作为@temp t1中的行号,按t2.a+t2.b顺序按t1.a进行划分)
在t2.a=t1.b和t2.b=t1.a)c上连接温度t2
在c.a=t3.a和c.b=t3.b上连接温度t3
其中c.第1排
从@temp中选择*
发布只是为了向正在搜索相同内容的其他人显示更新的语法。+1,我不得不说,经典的重复删除策略。伙计,我以前在桌子上用过这个,因为我的同龄人认为一个独特的约束太荒谬了!