我正在尝试根据表B中的描述字段更新表A中的税区代码字段。
表B如下。说明是(州-县-市-邮政编码)
Code Description
10001 TX-Denton-Frisco-75033
表A的每个字段都分开,并且没有郡县字段,我需要根据城市,州和邮政编码来进行最小匹配。
City State Post Code
Frisco TX 75033
在下面的代码中,我仅根据邮政编码进行了匹配,但我需要一种根据城市,州和邮政编码进行匹配的方法。
UPDATE Table A
SET [Tax Area Code] = b.[Code]
FROM Table B AS b
JOIN Table A AS a
ON a.[Post Code]=RIGHT(b.[Description],5)
答案 0 :(得分:1)
假设数据始终遵循State-county-city-zipcode的格式,并且这些部分都不应丢失,那么您将获得JOIN
的信息:
WITH TableB AS(
SELECT 10001 AS Code,
'TX-Denton-Frisco-75033' AS [Description]
UNION ALL
SELECT 10002 AS Code,
'MA-Denton-South-Boston-01036' AS [Description]
UNION ALL
SELECT 10002 AS Code,
'FL-Florida-State-Florida-79841' AS [Description]),
TableA AS(
SELECT 'Frisco' AS City,
'TX' AS [State],
75033 AS PostCode
UNION ALL
SELECT 'South-Boston' AS City,
'MA' AS [State],
01036 AS PostCode
UNION ALL
SELECT 'Florida' AS City,
'FL' AS [State],
79841 AS PostCode)
SELECT *
FROM TableA A
LEFT JOIN TableB B ON B.[Description] LIKE CONCAT(A.[state],'-%','-',A.City,'-',RIGHT(CONCAT('00000',A.PostCode),5));
但是效果如何...现在这是一个完全不同的问题(但我建议的不是很好)。
答案 1 :(得分:1)
尝试一下,
WITH TableB AS(
SELECT 10001 AS Code,
'TX-Denton-Frisco-75033' AS [Description]),
TableA AS(
SELECT 'Frisco' AS City,
'TX' AS [State],
75033 AS PostCode)
SELECT * FROM TableA A
JOIN TableB B ON
a.State=Substring(B.[Description],1, CHARINDEX('-', B.[Description],-1)-1)
And a.City=Substring (B.[Description],PATINDEX('%' + A.city + '%',B.[Description]) , len(a.city))
And a.PostCode=RIGHT(b.[Description],5)