从表中删除具有相同Id的重复行

时间:2013-09-24 09:28:21

标签: sql sql-server sql-server-2008

我有一张表Emp,有这样的记录

Id     Name
1      A
2      B
3      C
1      A
1      A
2      B
3      C

现在我想删除表中的重复行 我正在使用此查询来选择或计算重复记录的数量

SELECT NameCol, COUNT(*) as TotalCount FROM TestTable 
GROUP BY NameCol HAVING COUNT(*) > 1 
ORDER BY COUNT(*) DESC

我应该写什么查询来删除表中的重复行。

如果我编写此查询以删除重复记录,那么它会给出(0) row Affected结果。

`DELETE FROM TestTable 
    WHERE ID NOT IN ( SELECT MAX(ID) FROM 
                                     TestTable 
                                     GROUP BY NameCol
                    )`

3 个答案:

答案 0 :(得分:4)

对于sqlserver 2005 +

TESTDATA:

declare @t table(Id int, Name char(1))
insert @t values
(1,'A'),(2,'B'),(3,'C'),(1,'A'),(1,'A'),(2,'B'),(3,'C')

删除声明(用你的Emp表替换@t)

;with a as
(
select row_number() over (partition by id, name order by id) rn
from @t
)
delete from a where rn > 1

select * from @t

答案 1 :(得分:1)

Here是这个问题的详细答案。您可以关注作者的工作或接受的答案中更有效但更复杂的工作

答案 2 :(得分:-2)

**Q How to Remove duplicate data with help of Rowid**   


create table abcd(id number(10),name varchar2(20))

insert into abcd values(1,'abc')

insert into abcd values(2,'pqr')


insert into abcd values(3,'xyz')

insert into abcd values(1,'abc')

insert into abcd values(2,'pqr')

insert into abcd values(3,'xyz')


select * from abcd

id  Name
1   abc
2   pqr
3   xyz
1   abc
2   pqr
3   xyz

Delete Duplicate record but keep Distinct Record in table 

DELETE 
FROM abcd a
WHERE ROWID > (SELECT MIN(ROWID) FROM abcd b
WHERE b.id=a.id
);

run the above query 3 rows delete 

select * from abcd

id  Name 
1   abc
2   pqr
3   xyz