刪除完全一樣的重複資料, 保留其中一條

2021-06-16 18:00:13 字數 2191 閱讀 2348

--1. 刪除已存在表.  

if exists (

select 1 from sysobjects where id = object_id(n'test') and objectproperty(id, n'isusertable') = 1

) begin

drop table test

end

go--2. 建表

create table [dbo].test( [userid] [int] not null, [name] varchar(20) not null,isenabled bit)

goinsert into dbo.test

select 1,'aa',0 union all --注:只能用 union, 不能用 union all. 要不只會有一條記錄

select 1,'aa',1 union all

select 2,'bb',0 union all

select 2,'bb',0 union all

select 2,'cc',1 union all

select 3,'dd',0

go--如果有檢視先刪除

if exists(select 1 from sys.views where name='tmp_view_test')

drop view tmp_view_test

go--建立檢視 (注:partition by的功能為以***列來分組, 有點相當於group by)

--盡可能刪除 isenabled = 0 的記錄

create view tmp_view_test as

select row_number() over(partition by [userid] order by isnull(isenabled,0) desc) as num,*

from test

go--刪除前情況

select * from tmp_view_test order by userid,num

--刪除重複

delete from tmp_view_test where num!=1

--刪除後情況

select * from tmp_view_test order by userid,num

不用檢視刪除:

--1. 刪除已存在表.  

if object_id(n'test') is not null

begin

drop table test

end

go--2. 建表

create table [dbo].test( [userid] [int] not null, [name] varchar(20) not null,isenabled bit)

goset nocount on

insert into dbo.test

select 1,'aa',0 union all --注:只能用 union, 不能用 union all. 要不只會有一條記錄

select 1,'aa',1 union all

select 2,'bb',0 union all

select 2,'bb',0 union all

select 2,'cc',1 union all

select 3,'dd',0

goselect * from test

/*userid name isenabled

1 aa 0

1 aa 1

2 bb 0

2 bb 0

2 cc 1

3 dd 0

*/delete from tmp from

(select row_number() over (partition by userid order by isenabled desc) as rid,* from test) as tmp

where rid!=1

select * from test

/*userid name isenabled

1 aa 1

2 cc 1

3 dd 0

*/

MySQL刪除重複資料,只保留其中最大id的一條

今天同事寫了個刪除重複資料保留一條記錄的資料庫語句,問我錯在哪兒,正好給大家講講 注 以下語句只單對mysql資料庫 語句 問題 delete from show where id not in select max id from show where led 43 and location an...

sql 刪除重複資料 保留乙個

方法1 1 建立乙個臨時表,選取需要的資料。2 清空原表。3 臨時表資料匯入到原表。4 刪除臨時表。mysql select from student id name 11 aa 12 aa 13 bb 14 bb 15 bb 16 cc 6 rows in set mysql create tem...

SQL刪除重複資料,並保留GUID最小的一條資料

操作步驟 1 首先,查詢表中每乙個重複資料的最小guid的一條資料,重覆記錄是根據單個字段 repeat 來判斷 select from table t where t.guid select min a.guid from table a where a.repeat t.repeat 2 查出除...