2017-03-29 64 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很高興幫助。乾杯:) –