日期:2014-05-17 浏览次数:20572 次
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 Users select 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);
go
select distinct * into tmp from users
truncate table users
insert into users select * from tmp
drop table tmp
select * 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 tablename
delete from tablename
insert into tablename select * from temp