5

我有一个名为Housessql server 数据库的表,该表有一列包含(丹麦)地址。在丹麦,街道名称总是在门牌号之前,如果是公寓,则在公寓信息之前。我想将街道名称和号码分成两个字符串,而忽略公寓信息。我的数据如下所示:

Address
Fisker Vejen 48B, 1.TV
Baunevej 29

因此,有些街道名称超过 1 个单词,有些地址包含公寓信息,有些则没有。一些门牌号码也有非数字字符。我希望它是:

Street_Name      House_Number
Fisker Vejen     48B
Baunevej         29

我可以使用以下代码提取街道名称:

select case when a.NumStart> 0 then LEFT(a.Address,a.NumStart-1) ELSE a.Address END as Street_Name,
    FROM
    (select patindex('%[0-9]%',Address) as [NumStart], Address from Houses) a

但是没有楼层信息我不能得到门牌号。任何人都可以帮忙吗?

谢谢!

4

3 回答 3

4

这是一个解决方案:

SELECT *
        ,LEFT(Address,PATINDEX('% [0-9]%',Address)-1)'Street'
        , SUBSTRING(Address,PATINDEX('% [0-9]%',Address)+1,PATINDEX('%[0-9],%',Address+ ',')-PATINDEX('% [0-9]%',Address))'House Number'
FROM T

演示:SQL 小提琴

更新:如果门牌号总是以数字开头,后跟逗号或根本没有,那么这将起作用:

SELECT *
        ,LEFT(Address,PATINDEX('% [0-9]%',Address)-1)'Street'
        , SUBSTRING(Address,PATINDEX('% [0-9]%',Address)+1,PATINDEX('%, %',Address+ ', ')-PATINDEX('% [0-9]%',Address)-1)'House Number'
FROM Table1

Demo2:SQL Fiddle2

于 2013-06-25T21:06:37.473 回答
1
SELECT 
  Vejnavn, 
  case when NumEnd > 0 then left(rest,NumEnd-1) else rest end Housenumber 
FROM ( 
  SELECT 
    *, 
    patindex('%[^0-9A-Z]%',rest) numend 
  FROM (
    SELECT 
      CASE WHEN a.NumStart> 0 THEN LEFT(a.Adresse,a.NumStart-1) ELSE a.Adresse END as Vejnavn,
      CASE WHEN a.NumStart> 0 THEN SUBSTRING(a.Adresse,a.NumStart,100) ELSE '' END rest
    FROM (
      SELECT 
        PATINDEX('%[0-9]%',Adresse) AS [NumStart], 
        Adresse 
      FROM Houses
    ) a
   ) b 
 ) c 

sqlfiddle

于 2013-06-25T21:17:44.153 回答
0

尝试这样的事情:

SELECT
  CASE WHEN  a.NumStart> 0 then LEFT(a.Adresse, a.NumStart-1) ELSE a.Adresse END as Vejnavn,
  Substring(a.adress, a.Numstart, a.Comma - a.Numstart + 1) as HouseNumber
FROM (
  SELECT 
    PATINDEX('%[0-9]%', Adress) as [NumStart], 
    CHARINDEX(',', Adress + ',') as Comma,
    Adresse, 
    Salgsdato 
  FROM Houses) a
于 2013-06-25T21:01:11.030 回答