2017-03-29 36 views
0

我正在寻找基于共有多少个字符出现的“地址”两列地址。下面是数据的显示方式和预期结果。任何解决方案将不胜感激。T-SQL:比较值匹配的返回值出现

enter image description here

+0

只是为了确认:空间不计为字符,123富苯乙烯/ 321 Foooo St为只有8,而不是10,并且同样地123 Foooo圣/ 321的Foo St为8只,而不是10? –

+0

这是正确的空间不算作一个字符。 –

+1

https://www.simple-talk.com/blogs/string-comparisons-in-sql-the-longest-common-substring/?注意:这是一个相对昂贵的事情来计算 –

回答

0

随着帮助下表值函数且跨应用

Declare @YourTable table (Address1 varchar(25),Address2 varchar(25)) 
Insert Into @YourTable values 
('123 Foo St','12 Foo'), 
('123 Foo St','Bar Street'), 
('123 Foo St','321 Foo St'), 
('123 Foo St','Bar Lane') 


Select A.* 
     ,B.* 
From @YourTable A 
Cross Apply (
       Select Cnt = count(*) 
       From (Select Distinct RetSeq,RetVal From [dbo].[udf-Str-Parse-Char](replace(A.Address1,' ',''))) C1 
       Join (Select Distinct RetVal From [dbo].[udf-Str-Parse-Char](replace(A.Address2,' ',''))) C2 
        on C1.RetVal=C2.RetVal 
      ) B 

返回

Address1 Address2 Cnt 
123 Foo St 12 Foo  5 
123 Foo St Bar Street 2 
123 Foo St 321 Foo St 8 
123 Foo St Bar Lane 0 

的UDF如果有意

CREATE FUNCTION [dbo].[udf-Str-Parse-Char] (@String varchar(max)) 
Returns Table 
As 
Return (
    with cte1(N) As (Select 1 From (Values(1),(1),(1),(1),(1),(1),(1),(1),(1),(1)) N(N)), 
      cte2(N) As (Select Top (IsNull(DataLength(@String),0)) Row_Number() over (Order By (Select NULL)) From cte1 a,cte1 b,cte1 c,cte1 d,cte1 e,cte1 f) 

    Select RetSeq=N 
      ,RetVal=Substring(@String,N,1) 
    From cte2 
) 
--Max 1 Million Observations 
--Select * from [dbo].[udf-Str-Parse-Char]('this is a string') 
+0

谢谢我可以与this.I投票,但作为一个新的参与者,它没有公开注册。再次感谢。 –

+0

@ M.Butter很高兴帮助。干杯:) –