总结:六种删除数据库重复行的方法

SQL Server删除重复行是我们最常见的操作之一,下面就为您介绍六种适合不同情况的SQL Server删除重复行的方法,供您参考。

创新互联-专业网站定制、快速模板网站建设、高性价比巴彦网站开发、企业建站全套包干低至880元,成熟完善的模板库,直接使用。一站式巴彦网站制作公司更省心,省钱,快速模板网站建设找我们,业务覆盖巴彦地区。费用合理售后完善,10多年实体公司更值得信赖。

1.如果有ID字段,就是具有唯一性的字段

 
 
 
  1. delect   table   where   id   not   in   (      
  2.   
  3. select   max(id)   from   table   group   by   col1,col2,col3...      
  4. )      

group by 子句后跟的字段就是你用来判断重复的条件,如只有col1,那么只要col1字段内容相同即表示记录相同。

2. 如果是判断所有字段也可以这样

 
 
 
  1. select   *   into   #aa   from   table   group   by   id1,id2,....      
  2. delete   table        
  3. insert   into   table        
  4. select   *   from   #aa  

3. 没有ID的情况

 
 
 
  1. select   identity(int,1,1)   as   id,*   into   #temp   from   tabel      
  2. delect   #   where   id   not   in   (      
  3. select   max(id)   from   #   group   by   col1,col2,col3...)      
  4. delect   table      
  5. inset   into   table(...)      
  6. select   .....   from   #temp  

4. col1+','+col2+','...col5 联合主键

 
 
 
  1. select   *   from     table   where   col1+','+col2+','...col5   in   (      
  2. select   max(col1+','+col2+','...col5)   from   table        
  3. where   having   count(*)>1      
  4. group   by   col1,col2,col3,col4        
  5. )   

group by 子句后跟的字段就是你用来判断重复的条件,如只有col1,那么只要col1字段内容相同即表示记录相同。

5.

 
 
 
  1. select   identity(int,1,1)   as   id,*   into   #temp   from   tabel      
  2. select   *   from     #temp   where   id   in   (      
  3. select   max(id)   from   #emp   where   having   count(*)>1   group   by   col1,col2,col3...)     

6.

 
 
 
  1. select   distinct   *   into   #temp   from   tablename        
  2. delete   tablename        
  3. go      
  4. insert   tablename   select   *   from   #temp   Sqlclub    
  5. go      
  6. drop   table   #temp  

分享标题:总结:六种删除数据库重复行的方法
网页地址:http://www.hantingmc.com/qtweb/news33/117833.html

网站建设、网络推广公司-创新互联,是专注品牌与效果的网站制作,网络营销seo公司;服务项目有等

广告

声明:本网站发布的内容(图片、视频和文字)以用户投稿、用户转载内容为主,如果涉及侵权请尽快告知,我们将会在第一时间删除。文章观点不代表本网站立场,如需处理请联系客服。电话:028-86922220;邮箱:631063699@qq.com。内容未经允许不得转载,或转载时需注明来源: 创新互联