SQL查询删除所有重复记录,但一个

标签 tsql duplicates sybase duplicate-removal

<分区>

Possible Duplicate:
delete duplicate records in SQL Server

我有一个表,其中唯一记录由复合键表示,例如 (COL_A, COL_B)。

我已使用以下查询检查并确认我的表中有重复行:

select COL_A, COL_B, COUNT(*)
from MY_TABLE
group by COL_A, COL_B
having count(*) > 1
order by count(*) desc

现在,我想删除所有重复的记录,但只保留一个。

有人可以阐明如何使用 2 列实现这一目标吗?

编辑: 假设表格只有 COL_ACOL_B

最佳答案

第一个解决方案, 它很灵活,因为您可以添加比 COL_ACOL_B 更多的列:

-- create table with identity filed
-- using idenity we can decide which row we can delete
create table MY_TABLE_COPY
(
  id int identity,
  COL_A varchar(30), 
  COL_B  varchar(30)
  /*
     other columns
  */
)
go
-- copy data
insert into MY_TABLE_COPY (COL_A,COL_B/*other columns*/)
select COL_A, COL_B /*other columns*/
from MY_TABLE
group by COL_A, COL_B
having count(*) > 1
-- delete data from  MY_TABLE
-- only duplicates (!)
delete MY_TABLE
from MY_TABLE_COPY c, MY_TABLE t
where c.COL_A=t.COL_A 
and c.COL_B=t.COL_B
go
-- copy data without duplicates
insert into MY_TABLE (COL_A, COL_B /*other columns*/)
select t.COL_A, t.COL_B /*other columns*/
from MY_TABLE_COPY t
where t.id = (
               select max(id) 
               from MY_TABLE_COPY c  
               where t.COL_A = c.COL_A
               and  t.COL_B = c.COL_B
             ) 
go

第二种解决方案 如果您在 MY_TABLE 中确实有两列,您可以使用:

-- create table and copy data
select distinct COL_A, COL_B
into MY_TABLE_COPY
from MY_TABLE
-- delete data from  MY_TABLE 
-- only duplicates (!)
delete MY_TABLE
from MY_TABLE_COPY c, MY_TABLE t
where c.COL_A=t.COL_A 
and c.COL_B=t.COL_B
go
-- copy data without duplicates
insert into MY_TABLE
select t.COL_A, t.COL_B
from MY_TABLE_COPY t
go

关于SQL查询删除所有重复记录,但一个,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12939893/

相关文章:

sql-server - NewID() 函数的说明

sql - 一对多查询选择所有父级和每个父级的单个顶级子级

sql - 如何将值 'NULL'输入到SQL Server中的nvarchar列中?

mysql - 从 MySQL 中的其他数据库链接表

powershell - Sybase Cursor在Powershell脚本中不起作用

mysql - 比较sql中的两个值

Perl - 从引用的@array 中删除重复项

php - 识别正在重复的字段!

c++ - 导出两个命名空间中的重复函数 (C++)

sybase - 如何计算我的数据库中的表/ View /索引的数量