Users中有三个字段:UserName、Sex、Age。若两条记录的三个字段都相同,则为重复。
为了方便大家,我把sql语句写出来,如下所示:
- SQL code
create table Users( [UserName] nvarchar(32) not null, [Sex] bit not null, [Age] int not null,);insert into Users values('王杰', 1, 40);insert into Users values('王杰', 1, 40);insert into Users values('王杰', 1, 40);insert into Users values('苏有朋', 1, 40);insert into Users values('苏有朋', 1, 40);insert into Users values('刘德华', 1, 40);insert into Users values('刘德华', 0, 40);
上面的的例子,执行完删除sql之后,最后要只剩下4条数据:
'王杰', 1, 40 (有三条重复的,删掉两条)
'苏有朋', 1, 40 (有两条重复的,删除一条)
'刘德华', 1, 40
'刘德华', 0, 40
谢谢大家!
------解决方案--------------------
建立个unique index,以后就没这麻烦事啦。
------解决方案--------------------
- SQL code
---先把符合条件记录放入一个临时表中,select distinct UserName,Sex,Age into #temp from Users----然后把原表删除掉 delete Users----然后把临时表记录插入insert into Usersselect UserName,Sex,Age from #temp
------解决方案--------------------
所有列都存在重复的话,需要借用临时表来实现.
- SQL code
create table Users( [UserName] nvarchar(32) not null, [Sex] bit not null, [Age] int not null,);insert into Users values('王杰', 1, 40);insert into Users values('王杰', 1, 40);insert into Users values('王杰', 1, 40);insert into Users values('苏有朋', 1, 40);insert into Users values('苏有朋', 1, 40);insert into Users values('刘德华', 1, 40);insert into Users values('刘德华', 0, 40);goselect distinct * into tmp from userstruncate table usersinsert into users select * from tmpdrop table tmpselect * from users/*UserName Sex Age -------------------------------- ---- ----------- 刘德华 0 40刘德华 1 40苏有朋 1 40王杰 1 40(所影响的行数为 4 行)*/drop table users
------解决方案--------------------
select username,sex,age from users group by username,sex,age
------解决方案--------------------
delete from (select run_number()over(order by username,sex,age) as odr from users)a
where a.odr<>1
------解决方案--------------------
- SQL code
create table Users( [UserName] nvarchar(32) not null, [Sex] bit not null, [Age] int not null,);insert into Users values('王杰', 1, 40);insert into Users values('王杰', 1, 40);insert into Users values('王杰', 1, 40);insert into Users values('苏有朋', 1, 40);insert into Users values('苏有朋', 1, 40);insert into Users values('刘德华', 1, 40);insert into Users values('刘德华', 0, 40);;with _a as( select row_number()over(partition by username,sex,age order by username) as coou,* from users)select username,sex,age from _a where coou=1
------解决方案--------------------
- SQL code
-- 查出数据插入新表select [UserName],[sex],[age] from ( select r=row_number() over (partition by [UserName],[sex],[age] order by newid()),* from users) a where a.r=1-- 删除旧表,新表.表名 = 旧表.表名
------解决方案--------------------
- SQL code
--删除重复记录--1),delete from tablename where id not in (select max(id) from tablename group by col1,col2,...)--2),select distinct * into temp from tablenamedelete from tablenameinsert into tablename select * from temp