连接具有不同长度列值的表

时间:2014-08-04 15:39:47

标签: tsql

我需要通过连接具有可变长度的表的列来获取ID。 表A有2列ID和PostCode

-----------------
| ID | PostCode |
|----|----------|
| 1  |    BR    |
|----|----------|
| 2  |    WT    |
|----|----------|
| 3  |    B71   |
|----|----------|
| 4  |    BR5   |
|----|----------|

表B包含名称和完整邮政编码

的列
|------|----------|
| Name | PostCode |
|------|----------|
| Mr X | CR2  5ER |
|------|----------|
| Ms Y | BT2  6ER |
|------|----------|
| XX   | B71  4WQ |
|------|----------|
| YY   | BR4  8ER |
|------|----------|
| SS   | BR5A 5RT |
|------|----------|

我需要获得Id 1 [BR-> BR4 8ER],3 [B71-> B71 4WQ]和4 [BR5-> BR5A 5RT] 我该如何开展这项工作?

4 个答案:

答案 0 :(得分:1)

select A.PostCode, B.PostCode as FullPostCode, B.Name
  from A
  join B 
    on substring(B.PostCode,0,len(A.PostCode)) =  A.PostCode 

答案 1 :(得分:1)

考虑邮政编码BR29 8LN。如果表A有代码B和BR,这个邮政编码将被捕获两次 - 不是OP想要的,而不是我想要的。

以下捕获所有内容,只要在邮政编码前缀之后,就会有一个数字划分邮政编码区域:

  select A.PostCode, B.PostCode as FullPostCode, B.Name
  from B
  inner join A 
    on substring(B.PostCode ,0,len(A.PostCode)+1) = A.PostCode
    WHERE IsNumeric(substring(B.PostCode ,len(A.PostCode)+1,1)) = 1

答案 2 :(得分:0)

您可能会这样做:

select A.PostCode, B.PostCode as FullPostCode, B.Name
from A
join B on B.PostCode like A.PostCode + '%'

答案 3 :(得分:0)

这可能有所帮助。

DECLARE @TableA TABLE (UserID INT,
                   PostCode VARCHAR(10))
DECLARE @TableB TABLE (Name VARCHAR(10),
                   PostCode VARCHAR(10))

INSERT INTO @TableA
VALUES
('1', 'BR'),
('2', 'WT'),
('3', 'B71'),
('4', 'BR5')

INSERT INTO @TableB
VALUES
('Mr X', 'CR2  5ER'),
('Ms Y', 'BT2  6ER'),
('XX', 'B71  4WQ'),
('YY', 'BR4  8ER'),
('SS', 'BR5A 5RT');
WITH CTE
    AS (
    SELECT CAST(UserID AS VARCHAR(10)) AS UserID,
         Name,
         tb.PostCode,
         ta.PostCode AS PostCode2
         ,
         ROW_NUMBER() OVER (PARTITION BY UserID ORDER BY tb.PostCode DESC) AS PcID
    FROM @TableA AS ta
        JOIN @TableB AS tb
        ON ta.PostCode = LEFT(tb.PostCode, LEN(ta.PostCode))
    )
, cte2
    AS (
    SELECT STUFF((SELECT ', ' + c2.UserID + ' [' + c2.PostCode2 + '-' + c2.PostCode + ']'
               FROM cte AS c2
               WHERE c1.UserID = c2.UserID
                AND PcID = 1
               FOR XML PATH('')), 1, 2, '') AS PostCodeMatch
    FROM cte AS c1
    WHERE PcID = 1
    )
    SELECT DISTINCT STUFF((SELECT ', ' + PostCodeMatch
                      FROM cte2 AS c2
                      FOR XML PATH('')), 1, 2, '') AS PostCodeMatch
    FROM cte2