--創建測試表 CREATE TABLE [dbo].[testtab]( [id] [nchar](10) NULL, [name] [nchar](10) NULL ) ; --向測試表插入測試數據 insert into testtab values('1','1'); insert into testtab values('1','1'); insert into testtab values('2','2'); insert into testtab values('2','2'); insert into testtab values('3','3'); insert into testtab values('3','3'); --創建臨時表並向臨時表中插入測試表testtab中數據以及添加自增id:autoID select identity(int,1,1) as autoID, * into #Tmp from testtab --根據autoID刪除臨時表#tmp中的重復數據,只保留每組重復數據中的第一條 delete #Tmp where autoID in(select max(autoID) from #Tmp group by id); --清除testtab表中的所有數據 delete testtab; --向testtab表中插入#Tmp表中被處理過的數據 insert into testtab select id,name from #Tmp; --刪除臨時表#Tmp drop table #Tmp;
看你的表結構,我簡單寫一條你參考一下:
Delete From table
where Id not in (Select min(id),column1,column2 From table group by column1,column2)
Delete from tablename where id not in (select max(id) from
tablename group by col1,col2,...)