程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 數據庫知識 >> 其他數據庫知識 >> 更多數據庫知識 >> SQL去除重復記錄(七種),sql去除重復七種

SQL去除重復記錄(七種),sql去除重復七種

編輯:更多數據庫知識

SQL去除重復記錄(七種),sql去除重復七種


話不多說,請看代碼:

if not object_id('Tempdb..#T') is null
 drop table #T
Go
Create table #T([ID] int,[Name] nvarchar(1),[Memo] nvarchar(2))
Insert #T
select 1,N'A',N'A1' union all
select 2,N'A',N'A2' union all
select 3,N'A',N'A3' union all
select 4,N'B',N'B1' union all
select 5,N'B',N'B2'
Go 

--I、Name相同ID最小的記錄(推薦用1,2,3),保留最小一條

方法1:

delete a from #T a where  exists(select 1 from #T where Name=a.Name and ID<a.ID)

方法2:

delete a from #T a left join (select min(ID)ID,Name from #T group by Name) b on a.Name=b.Name and a.ID=b.ID where b.Id is null

方法3:

delete a from #T a where ID not in (select min(ID) from #T where Name=a.Name)

方法4(注:ID為唯一時可用):

delete a from #T a where ID not in(select min(ID)from #T group by Name)

方法5:

delete a from #T a where (select count(1) from #T where Name=a.Name and ID<a.ID)>0

方法6:

delete a from #T a where ID<>(select top 1 ID from #T where Name=a.name order by ID)

方法7:

delete a from #T a where ID>any(select ID from #T where Name=a.Name)
select * from #T

以上就是本文的全部內容,希望本文的內容對大家的學習或者工作能帶來一定的幫助,同時也希望多多支持幫客之家!

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved