SqlServer 刪除重複資料

2022-09-14 12:03:14 字數 2231 閱讀 8587

一、過濾重複的資料

1、完全重複的記錄

select

distinct 欄位1,欄位2,欄位3 from 資料表

2、部分關鍵字段重複的記錄

/*

資料結構:角色檔案(角色編碼,角色,角色分類編碼)

功  能:取出指定字段(角色分類編碼)為關鍵字的無重複資料,重複的取第一條

說  明:重覆記錄取最後一條,只需要把min改成max即可

*/select

*from 角色檔案 t where 角色編碼 in (select

min(角色編碼) from 角色檔案 t1 group

by t1.角色分類編碼)

二、刪除重覆記錄

資料庫的使用過程中由於程式方面的問題有時候會碰到重複資料,重複資料導致了資料庫部分設定不能正確設定,本例舉出刪除它的辦法。

有兩個意義上的重覆記錄,一是完全重複的記錄,也即所有欄位均重複的記錄,二是部分關鍵字段重複的記錄,比如name欄位重複,而其他欄位不一定重複或都重複可以忽略。

1、對於第一種重複,比較容易解決,使用

select

distinct

*from tablename

就可以得到無重覆記錄的結果集。

如果該錶需要刪除重複的記錄(重覆記錄保留1條),可以按以下方法刪除

select

distinct

*into #tmp from

tablename

drop

table

tablename

select

*into tablename from

#tmp

drop

table #tmp

發生這種重複的原因是表設計不周產生的,增加唯一索引列即可解決。

2、這類重複問題通常要求保留重覆記錄中的第一條記錄,操作方法如下

假設有重複的字段為name,address,要求得到這兩個字段唯一的結果集

select

identity(int,1,1) as autoid, *

into #tmp from

tablename

select

min(autoid) as autoid into #tmp2 from #tmp group

byname,autoid

select

*from #tmp where autoid in(select autoid from #tmp2)

最後乙個select即得到了name,address不重複的結果集(但多了乙個autoid欄位,實際寫時可以寫在select子句中省去此列)

我的demo:

select

identity(int,1,1) as

autoid,

[productcode

] ,[

categoryid

]into #tmp from

dbo.tblproduct

select

min(autoid) as autoid into #tmp2 from #tmp group

byproductcode ,companyid

truncate

table

dbo.tblproduct

insert

into tblproduct( [

productcode

] ,[

categoryid])

select

[productcode

] ,[

categoryid

]from

#tmp

where autoid in(select autoid from

#tmp2)

select

count(*) from

#tmp

select

count(*) from

#tmp2

drop

table

#tmp

drop

table #tmp2

原文:

刪除重複資料

介紹兩種刪除重複行的方式 1.使用臨時表,分組找出重複部分的id進行刪除 刪除table goods info 中存在重複goods id的記錄 select identity int,1,1 as autoid,into temptable from goods info select min a...

sql server 去重複資料

方法一 select distinct into ttemp from dr task log 將dr task log中不重複的資料插入到臨時表ttemp中 drop table dr task log 刪除原來的表 select into dr task log from ttemp 將ttem...

sql刪除重複資料

1 建立表 create table dbo test id numeric 18,0 identity 1,1 not null primary key,name varchar 200 collate chinese prc ci as null remark varchar 1024 coll...