[求sql语句]表中数据有重复,怎么删掉重复的部分(重复的数据保留一条)
Users中有三个字段:UserName、Sex、Age。若两条记录的三个字段都相同,则为重复。
为了方便大家,我把sql语句写出来,如下所示:
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);
---先把符合条件记录放入一个临时表中,select distinct UserName,Sex,Age into #temp from Users----然后把原表删除掉 delete Users----然后把临时表记录插入insert into Usersselect UserName,Sex,Age from #temp
[解决办法]
所有列都存在重复的话,需要借用临时表来实现.
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
[解决办法]
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
[解决办法]
-- 查出数据插入新表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-- 删除旧表,新表.表名 = 旧表.表名
[解决办法]
--删除重复记录--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