sql去重查询语句

转自:https://blog.csdn.net/wuyoudeyuer/article/details/91384971

1. 存在两条一样的数据:

select distinct * from 表名 where 条件;

2. 存在部分字段相同:存在部分字段相同,就是有key id,即唯一键。如:id列不同,id类型为int,自增字段,使用聚合函数max或其他。

select * from 表名 where id in (select max (id)from 表名 group by   【去重复字段表1,.....】having count(*)>1);

3. 没有唯一键:

需要借助创建临时表来解决。

select  indentity (int,1,1) as  id , * into 临时表名  from 表名;

select * from newtable where  id in  (select max(id)  from newtable group by [去重复字段表1,.....]) drop table newtable

4. id列不同,id类型为unique identifier

① 使用row_number() over() partition by  给每一组添加行号

select *,(row_number() Over(partition By'分组字段' order By '排序字段')) RowNum from

(select * from table where '分组字段'in (select '分组字段' from table group by '分组字段' having count(*) >1)t1)

②将行号=1的数据插入临时表中

Select * into #A from (‘上面的sql语句’) t2 where t2.RowNum=1 

注意:

1.row_number() over()是给行加行号的;

2.partition by用于给结果集分组,如果没有指定那么它会把整个结果集作为一个分组。

原文地址:https://www.cnblogs.com/yuer02/p/14661001.html