SQL中的模糊连接

时间:2017-01-23 11:13:37

标签: sql sql-server

我希望有人可以为我解决我的问题。

我需要能够在SQL

中将以下两个表连接在一起

表1中某些列的值

QWERTY10
QAZWSXEDCR10
QAZWSXED1230

表2中某些列的值

QWWERTY20
QAZWSXEDCR20
QAZWSXED1240

我需要的结果是

QWERTY100000 QWERTY200000

QAZWSXEDCR10 QAZWSXEDCR20

QAZWSXED1230 QAZWSXED1240

现在,要将QWERTY10000链接到QWERTY20000,我需要对字段中值的前6个字符进行连接 但是要将QAZWSXEDCR10链接到QAZWSXEDCR20,我需要在字段中的值的前10个字符上进行连接。如果我只对前6个字符进行连接,那么我将获得重复。我会像这样说:

QAZWSXEDCR10 QAZWSXEDCR20

QAZWSXEDCR10 QAZWSXED1240

QAZWSXED1230 QAZWSXEDCR20

QAZWSXED1230 QAZWSXED1240

我还需要QAZWSXED1230QAZWSXED1240相关联,我需要在8个字符上进行联接才能使其正常工作。

我很难弄清楚如何将我的数据加入到一起。我想避免根据不同数量的字符进行10次不同的连接。 例如,首先加入6个字符,如果不成功,则在7,8,9和10上进行连接。 - 必须采用不同的方式......

有人可以在这推荐一个解决方案吗?

KR

3 个答案:

答案 0 :(得分:2)

正如Milney的评论中所提到的,PatIndex可能有助于找到第一个数字的字符串位置 - 如果适用的话还可以找到特殊字符。然后,您可以构造字符串匹配部分的子字符串

select  table1.col as col1,
        table2.col as col2
from    table1
        inner join
        table2
        on substring( table1.col, 1, patindex( '[0-9]', table1.col ) ) =
           substring( table2.col, 1, patindex( '[0-9]', table2.col ) )

答案 1 :(得分:1)

这是对Alex答案的修改,只是为了处理其中一个或两个值不包含数字的情况:

select t1.col as col1, t2.col as col2
from table1 t1 inner join
     table2 t2
     on left(t1.col, patindex('%[0-9]%', t1.col+'0')) = left(t2.col, patindex('%[0-9]%', t2.col+'0'));

答案 2 :(得分:0)

我认为这会有所帮助

Create table #table1 ( strValue varchar(100) ) 
Create table #table2 ( strValue varchar(100) ) 


Insert Into #table1 ( strValue ) Values
('QWERTY10'), ('QAZWSXEDCR10'),('QAZWSXED1230')

Insert Into #table2 ( strValue ) Values
('QWERTY20'), ('QAZWSXEDCR20'),('QAZWSXED1240')


Declare @MaxlengthT1 int, @MaxlengthT2 int
SELECT @MaxlengthT1 =  MAX(LEN(strValue)) FROM #table1
SELECT @MaxlengthT2 =  MAX(LEN(strValue)) FROM #table2


select  a.strValue  + REPLICATE('0',@MaxlengthT1 - LEN(a.strValue)) as col1,
        b.strValue  + REPLICATE('0',@MaxlengthT1 - LEN(b.strValue)) as col2
from    #table1 a 
        inner join
        #table2 b
        on substring( a.strValue, 0, patindex( '%[0-9]%', a.strValue )) =
           substring( b.strValue, 0, patindex( '%[0-9]%', b.strValue ))

DROP TABLE #table1 
DROP TABLE #table2
相关问题