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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM