写删除重复数据的命令
怎样写删除语句实现结果
最终结果是想把做一个触发器,每当有插入和更新的时候做个检查是否有重复的数据,如果有的话删除重复的记录,保留ID最大的一条
怎样写删除语句实现结果
最终结果是想把做一个触发器,每当有插入和更新的时候做个检查是否有重复的数据,如果有的话删除重复的记录,保留ID最大的一条
这个是你要的吗:
if OBJECT_ID('tb') is not null
drop table tb
go
create table tb
(
row_id int identity(48760,1),
CL_Code int,
No int,
Data varchar(20)
)
insert into tb
(CL_Code,No,Data)
select 213,1,'3+4' union all
select 213,1,'3+6' union all
select 213,1,'3+11' union all
select 213,1,'3+4' union all
select 213,1,'3+6' union all
select 213,1,'3+11' union all
select 213,2,'3+4' union all
select 213,2,'3+6' union all
select 213,2,'3+11' union all
select 213,2,'3+4' union all
select 213,2,'3+6' union all
select 213,2,'4+11' union all
select 213,2,'2 W' union all
select 213,2,'1+8' union all
select 213,2,'3+4' union all
select 213,2,'3+6' union all
select 213,2,'3+11' union all
select 213,2,'3+4' union all
select 213,2,'3+6' union all
select 213,2,'4+11' union all
select 213,2,'2 W' union all
select 213,2,'1+8' union all
select 213,2,'3+4' union all
select 213,2,'3+6' union all
select 213,2,'3+11' union all
select 213,2,'3+4' union all
select 213,2,'3+6' union all
select 213,2,'4+11'
delete from tb
where tb.row_id not in
(
select min(row_id) as row_id
from tb
group by cl_code,no,data
)
--查询剩余的数据
select *
from tb
/*
row_idCL_CodeNoData
4876021313+4
4876121313+6
4876221313+11
4876621323+4
4876721323+6
4876821323+11
4877121324+11
4877221322 W
4877321321+8
*/
lete from tb
from tb t1
inner join
(
select cl_code,no,data,
min(row_id) as row_id
from tb
group by cl_code,no,data
) t2
on t1.CL_Code = t2.CL_Code
and t1.No = t2.No
and t1.Data = t2.Data
and t1.row_id <> t2.row_id
--查询剩余的数据
select *
from tb
/*
row_idCL_CodeNoData
4876021313+4
4876121313+6
4876221313+11
4876621323+4
4876721323+6
4876821323+11
4877121324+11
4877221322 W
4877321321+8
*/