读书人

sql server 2008 R2 剔除数据表中多列

发布时间: 2013-06-25 23:45:41 作者: rapoo

sql server 2008 R2 删除数据表中多列属性重复的的记录

比如 有表stab,
有属性cl1,cl2,c3,cl4
我要删除表中存在这样行,比如row1,row2,删除row1中的cl1,cl2和row2 中的cl1和cl2分别相等的数据,也就是数据表中,部分属性重复的数据,使表中不存在重复数据


我写了如下语句
delete from stab as A
from A.cl1,A.cl2
in (select cl1,cl2 from stb group by cl1,cl2 having count(*) > 1)
and rowid not in (select min(rowid) from stab group by cl1,cl2 having count(*)>1)


这是从网上查的,但是提示where A.ListingId A.adId 有语法错误,好像只能写一个属性,另外rowid不识别


怎么回事呢,求高手帮忙




[解决办法]
我试了一下,上面的代码确实还有点问题,我改了一下:


create table stab(cl1 int,cl2 int,cl3 varchar(10),cl4 varchar(10))

--truncate table stab

insert stab (cl1,cl2,cl3,cl4)
values(1,1,'a','b'),
(1,2,'e','f'),

(2,1,'c','d'),

(3,1,'e','f'),
(3,2,'a','b'),

(2,1,'重复数据','d'), --与第2条数据重复重复数据

(1,1,'重复数据','f') --与第1条数据重复数据


select *
from stab




--会删除cl1和cl2这两列的数据相同的行,cl3和cl4列可以不同
--delete stab

with t1
as
(
select *,row_number() over(partition by cl1,cl2 order by cl1) as row
from stab
)

delete t1
from t1
inner join t1 as t2
on t1.cl1 = t2.cl1
and t1.cl2 = t2.cl2
and t1.row = t2.row

where t2.row >=2

读书人网 >SQL Server

热点推荐