测试例子
--创建一个#temp的临时表
create table #temp
(
ID int not null,
Name varchar(20) null
)
--在临时表内插入测试数据
insert into #temp(ID,Name) values('1','测试');
insert into #temp(ID,Name) values('1','测试');
insert into #temp(ID,Name) values('2','测试2');
insert into #temp(ID,Name) values('2','测试');
insert into #temp(ID,Name) values('3','测试');
//查询临时表
select * from #temp
解决方法
--查询去重并删除重复数据
with TEST as
(
select ID,Name,row_number() over(partition by ID,Name order by ID) RowNum
from #temp
)
delete from TEST where RowNum > 1
--查询去重后的数据
select * from #temp
有两个意义上的重复记录,一是完全重复的记录,也即所有字段均重复的记录,二是部分关键字段重复的记录,比如Name字段重复,而其他字段不一定重复或都重复可以忽略。
1、对于第一种重复,比较容易解决,使用
select distinct * from tableName
就可以得到无重复记录的结果集。
如果该表需要删除重复的记录(重复记录保留1条),可以按以下方法删除
select distinct * into #temp from tableName
drop table tableName
select * into tableName from #temp
drop table #temp
发生这种重复的原因是表设计不周产生的,增加唯一索引列即可解决。
2、这类重复问题通常要求保留重复记录中的第一条记录,操作方法如下
假设有重复的字段为title,要求得到这个字段唯一的结果集
delete companynews where id in
(
select id from (select title,max(id) as id ,count(*) as rcount from companynews group by title) a where rcount>1
)