重复几行

时间:2014-08-27 18:50:31

标签: sql sql-server database duplicate-removal

我有一张桌子:

model1 model2 speed  ram
-----  ------ ------ ----
1121   1233   750    128
1232   1233   500    64
1232   1260   500    32
1233   1121   750    128
1233   1232   500    64
1260   1232   500    32

我需要删除重复的model1和model2对。

这些行是4-6。看第一行:

model1 1121     model2 1233

副本是

model1 1233 model2 1121

如果model1 + model2 = model2 + model1 - 这是重复的。

我尝试过使用这样的问题:

where cast(model1 as char(4))+cast(model2 as char(4))<>cast(model1 as char(4))+cast(model2 as char(4))

。我该怎么做?谢谢。

4 个答案:

答案 0 :(得分:2)

未经测试,使用风险自负,但可以作为起点

仅查看唯一:

select model1,model2 from T
EXCEPT
select model2,model1 from T where model2 > model1;

答案 1 :(得分:1)

如果您想从结果中过滤掉重复项,看起来应该只是:

where cast(model1 as char(4))+cast(model2 as char(4))<>cast(model1 as char(4))+cast(model2 as char(4))
AND cast(model1 as char(4))+cast(model2 as char(4))<>cast(model2 as char(4))+cast(model1 as char(4))

如果要选择要删除的重复项,请将其翻过来:

where cast(model1 as char(4))+cast(model2 as char(4))=cast(model1 as char(4))+cast(model2 as char(4))
OR cast(model1 as char(4))+cast(model2 as char(4))=cast(model2 as char(4))+cast(model1 as char(4))

答案 2 :(得分:1)

要选择重复项,因为您已经定义了它们:

SELECT * 
FROM Table1 a
WHERE EXISTS (  SELECT *
                FROM Table1 b 
                WHERE  a.model1 = b.model2
                 AND   a.model2 = b.model1
             )
AND model2 < model1

演示:SQL Fiddle

答案 3 :(得分:1)

首先,你应该改进你的INSERTS,如果你在插入之前对你的值进行排序,那么就不应该有更多的重复。

要删除存在另一个已排序组合的所有行,请使用以下命令:

DELETE FROM table
FROM table t1
WHERE EXISTS (
  SELECT NULL
  FROM table t2 
  WHERE t2.model1 = t1.model2
  AND t2.model2 = t1.model1)
WHERE t1.model2 > t1.model1

这应该在mssql 2005及更高版本中有效,但我现在无法检查语法。将剩余数据更新为已排序列应该很简单:)