SQL Server数据库中如何查询重复数据并处理?

 时间:2026-02-14 11:50:13

1、数据准备:生成重复数据

SELECT name,object_id,type,type_desc,create_date,is_ms_shipped into temp_test  FROM sys.objects  

insert into temp_test

SELECT top 30 name,object_id,type,type_desc,create_date,is_ms_shipped  FROM sys.objects 

SQL Server数据库中如何查询重复数据并处理?

2、验证是否有重复数据方法一:

select name,object_id,type,type_desc,create_date,is_ms_shipped,count(*) from temp_test

group by name,object_id,type,type_desc,create_date,is_ms_shipped having count(*) >1

SQL Server数据库中如何查询重复数据并处理?

3、验证是否有重复数据方法二:

select * from (

SELECT name,object_id,type,type_desc,create_date,is_ms_shipped,

ROW_NUMBER()over(partition by name,object_id,type,type_desc,create_date,is_ms_shipped order by name) as rk  

    FROM temp_test ) t where t.rk > 1

SQL Server数据库中如何查询重复数据并处理?

4、删除重复数据方法一:创建临时表

-- 取去重的数据到备份表

select distinct name,object_id,type,type_desc,create_date,is_ms_shipped into temp_test_new from temp_test

-- 删除重复数据表

drop table if exists temp_test

-- 修改备份表名为原来表名

EXEC sp_rename 'temp_test_new', 'temp_test' 

SQL Server数据库中如何查询重复数据并处理?

5、删除重复数据方法二:使用“with 子句 和 ROW_NUMBER()函数”来实现删除完全重复的其他行

WITH tab AS(  

    SELECT ROW_NUMBER()over(partition by object_id order by  object_id) as rk

    FROM temp_test

)DELETE FROM tab WHERE rk>1 

SQL Server数据库中如何查询重复数据并处理?

1、要明确通过哪些维度来定位数据时重复的;

2、要学会查找重复数据方法;

3、要学会删除重复数据的方法。

  • 怎样使用VBA每隔三行选一行?
  • linux 给所有文件下文件加权限
  • Excel:如何将二进制文本转换为十进制数
  • C#如何删除没用的Using引用
  • Notepad++标签显示橙色条如何去掉呢?
  • 热门搜索
    3d太湖字谜总汇大全 玉米怎么做好吃 小龙虾怎么做好吃 经痛怎么缓解 直肠炎最佳治疗方法 凯文怎么了 方法派 辣椒酱的家常做法 回奶的正确方法 排毒方法