SQL查詢語句去除重復行


1.存在兩條完全相同的紀錄

這是最簡單的一種情況,用關鍵字distinct就可以去掉

 

select distinct * from table(表名) where (條件)

 

 

2.存在部分字段相同的紀錄(有主鍵id即唯一鍵)

如果是這種情況的話用distinct是過濾不了的,這就要用到主鍵id的唯一性特點及group by分組

 

select * from table where id in (select min(id) from table group by [去除重復的字段名列表,....])

[取重復的第一行]

或者

select * from table where id in (select max(id) from table group by [去除重復的字段名列表,....])

[取重復的最后一行]

 

 

3.沒有唯一鍵ID

select identity(int,1,1) as id,* into newtable(臨時表) from table

select * from newtable where id in (select min(id) from newtable group by [去除重復的字段名列表,....])

drop table newtable

 

擴展:

1、identity(int,1,1) ——從1開始,每次遞增1

2、SELECT INTO 語句 —— SELECT * INTO new_table_name [IN externaldatabase] FROM old_tablename

 

 ------------------------------------------------------------------------------------------------------

引自:

sql查詢語句去除重復列(行)【http://blog.knowsky.com/234240.htm】


免責聲明!

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



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