日期:2014-05-18  浏览次数:20432 次

查找出重复的物料
编 码 名 称
3011003001 (Q40305) 
3011003011 (Q40305彩锌)
3011003003 (Q403018)
3011003012 (Q403018红锌)
....... ......

根据上面数据显示名称这里有很多类似,比如(Q40305)和(Q40305彩锌)只多了彩锌两个字,如何删除名称为(Q40305)
保留(Q40305彩锌)?
谢谢!


------解决方案--------------------
SQL code

--> 测试数据:[test]
if object_id('[test]') is not null 
drop table [test]
create table [test](
[编码] varchar(12),
[名称] varchar(11)
)
go
insert [test]
select '3011003001','Q40305' union all
select '3011003011','Q40305彩锌' union all
select '3011003003','Q403018' union all
select '3011003012','Q403018红锌'
go
--更正一下
delete from test 
where PATINDEX('%[0-9]%',REVERSE([名称]))=1
select * from test
/*
编码    名称
---------------------------------
3011003011    Q40305彩锌
3011003012    Q403018红锌
*/

------解决方案--------------------
如果长度是固定的,可以尝试以下方法
SQL code
if object_id('[tb]') is not null drop table [tb]
go
create table [tb]([编码] bigint,[名称] varchar(13))
insert [tb]
select 3011003001,'(Q40305)' union all
select 3011003011,'(Q40305彩锌)' union all
select 3011003003,'(Q403018)' union all
select 3011003012,'(Q403018红锌)'
go

delete tb
where exists(select 1 from tb a where left(tb.名称,7)=left(a.名称,7) and len(a.名称)>len(tb.名称))
go

select * from tb
/**
编码                   名称
-------------------- -------------
3011003011           (Q40305彩锌)
3011003012           (Q403018红锌)

(2 行受影响)

**/

------解决方案--------------------
SQL code
--> 测试语句:
DELETE t FROM [tb] AS t
WHERE EXISTS
    (
    SELECT 1 FROM [tb] 
    WHERE REPLACE([名称],')','') LIKE REPLACE(t.[名称],')','')+'%' 
    AND REPLACE(t.[名称],')','') NOT LIKE REPLACE([名称],')','')+'%'
    )

SELECT * FROM [tb]
/*
编码                   名称
-------------------- -------------
3011003011           (Q40305彩锌)
3011003012           (Q403018红锌)

(2 行受影响)


*/