Questions[SQL]:SQL删除重复记录
Q:删除某字段中的重复记录,Table1006表中有Id和Phone字段,Id为不重复的标字段,但是Phone含有重复字段,现在需要重复Phone记录行删除掉,只保留最新一条记录。
A:
if OBJECT_ID('dbo.Table1006') is not null
drop table dbo.Table1006
create table dbo.Table1006
(
[Id] int,
[Phone] varchar(10)
)
insert into dbo.Table1006 values(1, 100)
insert into dbo.Table1006 values(2, 110)
insert into dbo.Table1006 values(3, 120)
insert into dbo.Table1006 values(4, 130)
insert into dbo.Table1006 values(5, 110)
insert into dbo.Table1006 values(6, 110);
insert into dbo.Table1006 values(7, 120);
delete from dbo.Table1006
where [Id] not in ( select max([Id]) as [Id]
from dbo.Table1006
group by [Phone])
select * from dbo.Table1006
drop table dbo.Table1006
drop table dbo.Table1006
create table dbo.Table1006
(
[Id] int,
[Phone] varchar(10)
)
insert into dbo.Table1006 values(1, 100)
insert into dbo.Table1006 values(2, 110)
insert into dbo.Table1006 values(3, 120)
insert into dbo.Table1006 values(4, 130)
insert into dbo.Table1006 values(5, 110)
insert into dbo.Table1006 values(6, 110);
insert into dbo.Table1006 values(7, 120);
delete from dbo.Table1006
where [Id] not in ( select max([Id]) as [Id]
from dbo.Table1006
group by [Phone])
select * from dbo.Table1006
drop table dbo.Table1006