sqlserver查询重复数据,删除并保留一条。

本文介绍了在SQL Server中如何查找并删除重复数据。首先,通过创建临时表存储重复记录,然后使用GROUP BY和HAVING子句筛选出重复项。接着,利用NOT IN操作符从原始表中删除重复数据,确保每组重复数据只保留一条记录。这种方法适用于多字段的查重和删除,确保数据的唯一性。
摘要由CSDN通过智能技术生成

简单版本

  select max(id) as id,count(DslSku) as 重复数量,DslSku into #temp from ProductCheck_Code group by DslSku having(DslSku)>1

  select * from  ProductCheck_Code where id not in(select id From #temp) 
  drop table #temp

多字段查重

·先存入临时表再进入重复数据查询·

 select  dy.productId,dy.goodsNo,dy.skuid,sc.DouYinStoreNo,sit.goodsqty,sit.placepointid  
  into #temp from lswx.dbo.MedicineInfo_DouYin dy   left join dsl.dbo.Store_inventory_table  sit  
  on dy.goodsNo=sit.DslGoodsId left join dsl.dbo.StoreCheck_Code sc on sc.DslStoreNo=sit.DslStoreId 
  and sc.DouYinStoreNo<>'-' where sit.isChange_DouYin=1 and sc.DouYinStoreNo is not null

SELECT a.* FROM #temp a,
(
SELECT productId,placepointid FROM #temp
GROUP BY placepointid,productId
HAVING COUNT(1)>1
) AS b
WHERE a.productId=b.productId AND a.placepointid=b.placepointid

drop table #temp

查询重复数据

	  select *  from SHSJ0101 where  XSDM in (select XSDM from SHSJ0101 where SHSJPCDM = 'b1f492d67da743dc838e214195a2a524'  group by XSDM having count(XSDM) > 1) and SQSJ not in(select  max(SQSJ) from SHSJ0101 where SHSJPCDM = 'b1f492d67da743dc838e214195a2a524' group by  XSDM having count(XSDM) > 1 )and SHSJPCDM = 'b1f492d67da743dc838e214195a2a524'  

删除重复数据只保留一条

delete from SHSJ0101 where  XSDM in (select XSDM from SHSJ0101 where SHSJPCDM = 'b1f492d67da743dc838e214195a2a524'  group by XSDM having count(XSDM) > 1) and SHSJPCDM = 'b1f492d67da743dc838e214195a2a524'  and SQSJ not in(select  max(SQSJ) from SHSJ0101 where SHSJPCDM = 'b1f492d67da743dc838e214195a2a524' group by  XSDM having count(XSDM) > 1 )  
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

或与且与或非

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值