日期:2014-05-17  浏览次数:20512 次

写删除重复数据的命令

怎样写删除语句实现结果

最终结果是想把做一个触发器,每当有插入和更新的时候做个检查是否有重复的数据,如果有的话删除重复的记录,保留ID最大的一条


------解决方案--------------------
引用:
Quote: 引用:

Quote: 引用:


怎样写删除语句实现结果

最终结果是想把做一个触发器,每当有插入和更新的时候做个检查是否有重复的数据,如果有的话删除重复的记录,保留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_id CL_Code No Data
48760 213 1 3+4
48761 213 1 3+6
48762 213 1 3+11
48766 213 2 3+4
48767 213 2 3+6
48768 213 2 3+11
48771 213 2 4+11
48772 213 2 2 W
48773 213 2 1+8
*/


消息 147,级别 15,状态 1,第 4 行
聚合不应出现在 WHERE 子句中,除非该聚合位于 HAVING 子句或选择列表所包含的子查询中,并且要对其进行聚合的列是外部引用。


我用的是SQL Server 2008r2,完全可以运行,你用的是什么数据库?
------解决方案--------------------
要不改成这样试试: