通过部分字符串匹配

时间:2016-04-18 16:48:54

标签: sql sql-server

我有一个表mytable,其中ID带有前导零和“重复”,没有前导零。即我有2行,一行是456,另一行是000456。前导零的最大数据长度是6个字符。我需要根据一个有前导零的事实返回匹配,而另一个则没有。

我试过了:

SELECT constituent_id,  RIGHT('000000'+ISNULL(id,''),6) as missingbutpadded    
from mytable 
where id is not null and id not like '0%' 

这将返回第一列没有前导零和第二列中相同的值,前导零最多6个字符。如何匹配带前导零的那些?

现在是表格: mytable

|system_id| id   |first_name |last_name 
|1        |000456|James      | Smith    
|2        |456   |James      |Smith 
|3        |000555|Mary       |Carl  
|4        |555   |mary       |Carl  

Expected_Results

system_id |id    |matchedto |first_name |last_name
2         | 456  |000456    |James      |smith
4         | 555  |000555    |Mary       |Carl

1 个答案:

答案 0 :(得分:1)

select table1.Id as MatchId, table2.Id as MatchedId
from yourtable table1
inner join yourtable table2 ON Convert(int,table1.Id)=Convert(int,table2.Id)
Where table1.id<>table2.id and table2.id like '0%'

这将做你想要的。

这是一个测试

create table #mytable(id varchar(50))
insert into #mytable(id) values ('45'), ('0056'),('0045')

select table1.Id as MatchId, table2.Id as MatchedId
from #mytable table1
inner join #mytable table2 ON Convert(int,table1.Id)=Convert(int,table2.Id)
Where table1.id<>table2.id and table2.id like '0%'

(3排受影响) MatchId MatchedId

45 0045

(1行受影响)

相关问题