轉自: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用於給結果集分組,如果沒有指定那么它會把整個結果集作為一個分組。