SQLServer2000刪除重複數據(總結)轉帖

*******************************************
SQLServer2000刪除重複數據(總結)
*******************************************
 
一、具有主鍵的情況
 
I.具有唯一性的字段id(爲唯一主鍵)

 

delete  用戶表   
where  id  not  in   

select  max(id)  from  用戶表  group  by  col1,col2,col3... 

group  by  子句後跟的字段就是你用來判斷重複的條件,如只有col1, 
那麼只要col1字段內容相同即表示記錄相同。 
 
II.具有聯合主鍵
 
假設col1+','+col2+','...col5  爲聯合主鍵

(找出相同記錄)

 

select  *  from    用戶表  where  col1+','+col2+','...col5  in 

  select  max(col1+','+col2+','...col5)  from  用戶表   
  group  by  col1,col2,col3,col4
  having  count(*)>1    

group  by  子句後跟的字段就是你用來判斷重複的條件, 
如只有col1,那麼只要col1字段內容相同即表示記錄相同。 
 
或者:
(找出相同記錄)

 

select  *  from  用戶表  where  exists  (select  1  from  用戶表  x  where  用戶表.col1 =  x.col1  and   
用戶表.col2=  x.col2  group  by  x.col1,x.col2  having  count(*)  >1) 

 
III:判斷所有的字段

 

   select  *  into  #aa  from  用戶表  group  by  id1,id2,.... 
   delete  用戶表   
   insert  into  用戶表 select  *  from  #aa 

 
二、沒有主鍵的情況 
 
I.用臨時表實現 

 

select  identity(int,1,1)  as  id,*  into  #temp  from  用戶表 
delete  #temp   
where  id  not  in   

   select  max(id)  from  #  group  by  col1,col2,col3... 

delete  用戶表  ta 
inset  into  ta(...) select  .....  from  #temp 

 
II.用改變表結構(加一個唯一字段)來實現

 

alter  用戶表  add    newfield  int  identity(1,1) 
delete  用戶表 
where  newfield  not  in 

select  min(newfield)  from  用戶表  group  by  除newfield外的所有字段 

alter  用戶表  drop  column  newfield

 

文章出處:http://www.diybl.com/course/7_databases/sql/sqlServer/2007926/73829.html

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章