我有一种情况,我希望将地址拆分为Street Number
和Street Name
。
示例数据
在这些示例中,粗体部分为Street Number
,其余为Street Name
。
到目前为止,我目前的努力并没有帮助我。有人能快速解决这个问题吗?
-Key是地址的Street Number
部分,最后一次出现的数字结束。
答案 0 :(得分:4)
如果字符串模式一致,您可以使用
select
ltrim(rtrim(reverse(substring(reverse(address),patindex('%[0-9]%',reverse(address)),len(address))))) as streetNum,
ltrim(rtrim(reverse(substring(reverse(address),1,patindex('%[0-9]%',reverse(address))-1)))) as streetName
from tbl
使用patindex
在反向字符串中查找第一个数字的出现位置,并使用substring
和reverse
将它们拆分为单独的字段。
答案 1 :(得分:3)
示例强>
Declare @YourTable Table ([Id] varchar(50),[Addr] varchar(50))
Insert Into @YourTable Values
(1,'1093 Hundred Line Road')
,(2,'Flat 4442 Holly StreetAvondale')
,(3,'Apartment 1401/142 Shakespeare Road')
,(4,'Unit K109 Northbridge 45 Akoranga Drive, Northcote')
Select ID
,Addr1 = left(Addr,len(Addr)-patindex('%[0-9]%',reverse(Addr))+1)
,Addr2 = ltrim(right(Addr,patindex('%[0-9]%',reverse(Addr))-1))
From @YourTable
或只是为了好玩 - 使用交叉应用
Select ID
,Addr1 = substring(Addr,1,B.Pos)
,Addr2 = ltrim(substring(Addr,B.Pos+1,100))
From @YourTable
Cross Apply (values (len(Addr)-patindex('%[0-9]%',reverse(Addr))+1)) B(Pos)
<强>返回强>
ID Addr1 Addr2
1 1093 Hundred Line Road
2 Flat 4442 Holly StreetAvondale
3 Apartment 1401/142 Shakespeare Road
4 Unit K109 Northbridge 45 Akoranga Drive, Northcote
我应该注意:
解析地址可能是一个滑坡。请考虑以下事项:Address standardization within a database
答案 2 :(得分:1)
另一种选择......
IF OBJECT_ID('tempdb..#Address', 'U') IS NOT NULL
DROP TABLE #Address;
CREATE TABLE #Address (
StreetAddress VARCHAR(50) NOT NULL
);
INSERT #Address (StreetAddress) VALUES
('1093 Hundred Line Road'),
('Flat 4442 Holly StreetAvondale'),
('Apartment 1401/142 Shakespeare Road'),
('Unit K109 Northbridge 45 Akoranga Drive, Northcote');
-- SELECT * FROM #Address a;
--========================================================
SELECT
*,
StreetNum = LEFT(a.StreetAddress, sl.SplitLocation),
StreetName = SUBSTRING(a.StreetAddress, sl.SplitLocation + 1, 50)
FROM
#Address a
CROSS APPLY ( VALUES (PATINDEX('%[^0-9] [0-9]%', REVERSE(a.StreetAddress))) ) rs (ReverseSplit)
CROSS APPLY ( VALUES (LEN(a.StreetAddress) - rs.ReverseSplit) ) sl (SplitLocation);
HTH,Jason