基本上我试图获取一列的地址字段并将其分成三列,第一列具有地址编号,第二列具有街道名称,第三列具有地址#或者很多#
Address
-------------------
990 A street Apt 1B
127 B street Lot 3
到目前为止,我有这个适用于号码和街道。
Select LEFT(MP.[ADDRESS],PATINDEX('%[0-9][^0-9]%', MP.[ADDRESS] )) AS Number,
LTRIM(RIGHT(MP.[ADDRESS], LEN(MP.[ADDRESS]) - PATINDEX('%[0-9][^0-9]%', MP.[ADDRESS] ))) As Street
From MPFILE mp
它最终会像这样:
Number | Street
----------------------------
990 | A street Apt 1B
127 | B Street Lot 3
试图解决这个问题:
Number | Street | Apt/Lot
-----------------------------------
990 | A street | Apt 1B
127 | B street | Lot 3
答案 0 :(得分:2)
这样的东西可以用你给出的示例数据,但正如Gordon所说,地址很难解析,可能不应该用SQL解析。
WITH locations AS
(
SELECT ADDRESS,
LEN(ADDRESS) AS Len,
PATINDEX('%[0-9][^0-9]%', ADDRESS) AS NumLoc,
PATINDEX('%APT%', ADDRESS) AS APTLoc,
PATINDEX('%Lot%', ADDRESS) AS LotLoc
FROM MPFILE
), numbers AS
(
ADDRESS,
NumLoc,
Len - NumLoc AS StartAddr,
CASE WHEN APTLoc > 0 THEN AptLoc
WHEN LotLoc > 0 THEN LotLoc
ELSE Len AS EndAddr,
CASE WHEN APTLoc > 0 THEN AptLoc
WHEN LotLoc > 0 THEN LotLoc
ELSE Len AS StartApt,
Len AS EndApt
)
Select LEFT(NumLoc, MP.ADDRESS )) AS Number,
SUBSTRING(MP.ADDRESS, StartAddr, EndAddr),
SUBSTRING(MP.ADDRESS, StartApt, EndApt)
From numbers
答案 1 :(得分:0)
Declare @t table ( Address varchar(200));
Insert Into @t (Address) values
('990 A street Apt 1B'),
('127 B street Lot 3'),
('127 B street Lot 345'),
('4444 Rice Street Suite 105'),
('715 South King Street #200'),
('101 Aupuni Street Room 342')
Select Left(Address,CHARINDEX(' ',Address)) as Number,
SUBSTRING(Address,CHARINDEX(' ',Address)+1, CHARINDEX('street',SUBSTRING(Address,CHARINDEX(' ',Address)+1,LEN(Address)))+LEN('street')) as Street
,Substring(Address,CHARINDEX('street',Address)+LEN('street'),LEN(Address)) as [Apt/Lot]
From @t
**结果**
Number |Street |Apt/Lot
----------------------------|-------
990 |A street |Apt 1B
127 |B street |Lot 3
127 |B street |Lot 345
4444 |Rice Street |Suite 105
715 |South King Street |#200
101 |Aupuni Street |Room 342