SQL 刪除重複資料,只保留1條

2021-05-22 10:57:29 字數 2083 閱讀 7054

if not object_id('tempdb..#t') is null

drop table #t

gocreate 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...), 保留資料物理儲存最近一條

;with t as

(select rn = row_number()over(partition by [name ] order by getdate()), *

from  #t

)delete t

where  rn>1

或者;with t as

(select rn = row_number()over(partition by [name ] order by (select 1)), *

from  #t

)delete t

where  rn>1

--ii、name相同id最小的記錄(推薦用1,2,3),保留最小一條

方法1:

delete a from #t a where  exists(select 1 from #t where name=a.name and id0

方法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

生成結果:

/*id          name memo

----------- ---- ----

1           a    a1

4           b    b1

(2 行受影響)

*/--iii、name相同id保留最大的一條記錄:

方法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 max(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 max(id) from #t where name=a.name)

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

delete a from #t a where id not in(select max(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 desc)

方法7:

delete a from #t a where idselect * from #t

/*id          name memo

----------- ---- ----

3           a    a3

5           b    b2

(2 行受影響)

*/

SQL中刪除重複的行 重複資料 ,只保留一行

sql中刪除重複的行 重複資料 只保留一行 方法一 使用在t sql的程式設計中 分配乙個列號碼,以col1,col2組合來分割槽排序,刪除database重複的行 重複資料 只保留一行 col1,col2是資料庫database的字段 delete a from select col1,col2,...

sql去除重複資料 保留一條

去除重複資料 保留一條 delete from evaluation where id not in select max id from evaluation where convert varchar 100 adddate,23 2014 04 08 group by content id t...

SQL刪除重複的記錄 只保留一條

首先新建表 建立示例表 create tablet id intidentity 1,1 primary key,a varchar 10 b varchar 10 插入資料 insert into t select aa bb union allselect a1 bgb union allsel...