T-SQL:比较匹配的返回值

时间:2017-03-29 15:55:40

标签: sql sql-server tsql

我希望根据共有多少个字符“得分”两列地址。下面是数据的显示方式和预期结果。任何解决方案将不胜感激。

enter image description here

1 个答案:

答案 0 :(得分: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')