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

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

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

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.cnblogs.com/zhangshufeng/archive/2011/09/05/2167079.html

【编辑推荐】

  1. 养成一个SQL好习惯带来一笔大财富
  2. 告诉你,如何成就DBA职业生涯
  3. SQL Server性能调优之浅析SQL执行的过程
  4. 客户的一次疏忽,DBA的一次噩梦
  5. 数据库点滴之精妙SQL语句

 

 

 

责任编辑:艾婧 来源: 自 慎的博客
相关推荐

2010-10-22 16:29:11

SQL Server删

2011-03-08 08:59:01

SQL Server数数据移动

2011-05-24 10:54:15

数据库重复数据删除

2022-05-25 09:55:40

数据重复提交Java

2011-07-28 16:39:03

MySQL数据库修改MySQL密码

2017-10-27 11:47:05

SQL数据库优化

2018-04-27 13:00:00

数据库MySQL删除重复行

2011-01-12 21:26:49

2010-04-13 10:15:17

Oracle数据库

2010-09-01 16:55:55

SQL删除连接

2019-05-06 15:27:48

Oracle数据库数据

2023-06-01 16:45:11

React开发JavaScript

2011-03-14 15:47:33

Oracle数据库

2011-08-04 12:49:31

SQL Server数重复数据

2016-09-01 14:04:51

数据中心

2019-05-16 13:00:18

异步编程JavaScript回调函数

2011-05-24 14:13:20

Oracle数据库

2010-10-08 11:13:22

MySQL修改密码

2020-12-15 10:54:22

物联网互联网IoT

2023-08-15 15:44:55

React开发
点赞
收藏

51CTO技术栈公众号