我有一个表格,我想删除重复的行。重复行基于attributeID,section,keyid,productId和value字段。每个重复行都有唯一的ID productattributeID 。
以下脚本显示了哪些行重复:
select aa.attributeID,section,keyid,productID, value,count(*)
from productattribute PA
inner join AvailableAttribute AA on AA.AttributeID = PA.productID
group by aa.attributeID,section,keyid,productID, value
having count(*)>1
我正在努力编写一个脚本,它将删除除每行之外的所有行。 任何人都可以帮忙吗?
由于
答案 0 :(得分:1)
您可以这样做:
declare @productattribute as table(productattributeID int,section varchar(20),keyid int,productId int,value varchar(20))
declare @AvailableAttribute as table(attributeID int)
insert into @productattribute values(1,'a',10,20,'v')
insert into @productattribute values(2,'a',10,20,'v')
insert into @productattribute values(3,'a',10,20,'v')
insert into @productattribute values(4,'b',150,208,'vb')
insert into @productattribute values(5,'b',150,208,'vb')
insert into @productattribute values(6,'b',150,208,'vb')
insert into @productattribute values(7,'a',8,20,'v')
insert into @productattribute values(8,'a',10,19,'v')
insert into @AvailableAttribute values(20)
insert into @AvailableAttribute values(20)
insert into @AvailableAttribute values(20)
insert into @AvailableAttribute values(208)
insert into @AvailableAttribute values(208)
insert into @AvailableAttribute values(208)
insert into @AvailableAttribute values(20)
insert into @AvailableAttribute values(19)
select * from @productattribute
delete from @productattribute where productattributeID not in
(
select MIN(productattributeID) from @productattribute
where exists
(
select * from
(select section,keyid,productID,value,attributeID
from @productattribute inner join @AvailableAttribute on attributeID = productId
group by attributeID,section,keyid,productId,value) X
where X.attributeID=attributeID and X.keyid=keyid and X.productId=productId and X.section=section and X.value=value
) group by section,keyid,productId,value
)
select * from @productattribute