SQL去除重复记录(七种)
话不多说,请看代码:
ifnotobject_id('Tempdb..#T')isnull droptable#T Go Createtable#T([ID]int,[Name]nvarchar(1),[Memo]nvarchar(2)) Insert#T select1,N'A',N'A1'unionall select2,N'A',N'A2'unionall select3,N'A',N'A3'unionall select4,N'B',N'B1'unionall select5,N'B',N'B2' Go
--I、Name相同ID最小的记录(推荐用1,2,3),保留最小一条
方法1:
deleteafrom#Tawhere exists(select1from#TwhereName=a.NameandID<a.ID)
方法2:
deleteafrom#Taleftjoin(selectmin(ID)ID,Namefrom#TgroupbyName)bona.Name=b.Nameanda.ID=b.IDwhereb.Idisnull
方法3:
deleteafrom#TawhereIDnotin(selectmin(ID)from#TwhereName=a.Name)
方法4(注:ID为唯一时可用):
deleteafrom#TawhereIDnotin(selectmin(ID)from#TgroupbyName)
方法5:
deleteafrom#Tawhere(selectcount(1)from#TwhereName=a.NameandID<a.ID)>0
方法6:
deleteafrom#TawhereID<>(selecttop1IDfrom#TwhereName=a.nameorderbyID)
方法7:
deleteafrom#TawhereID>any(selectIDfrom#TwhereName=a.Name) select*from#T
以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,同时也希望多多支持毛票票!