从地址sql查询中分离城市名称

时间:2012-12-11 12:00:54

标签: sql sql-server street-address

我想将城市名称与数据库中的地址分开。

地址采用不同的格式 e.g

835 street no.3  Jalabad D.I. Khan ................ here city name is D.I khan
Ho. No. 102 St. No. 85  RawalPindi   ..........here city name is RawalPindi
h no.944 St. No.74  Karkhana road Gujrat   ......here city name is Gujrat
Ho. no.241 S No.26  I-8/3 Isb              .........here city name is isb

我这样做但它只适用于少数...我需要一个通用查询,可以适用于每种格式的地址

SELECT DISTINCT REVERSE
( 
  LEFT( REVERSE(All_Students.Address), CHARINDEX(' ', REVERSE(All_Students.Address))-1 ) 
) as Addresses
from All_Students
order by addresses

1 个答案:

答案 0 :(得分:2)

我们对这些地址字符串中的城市了解多少? City位于字符串的末尾,但它可以包含多个单词。所以我认为没有办法将仅使用此表从地址行中删除城市名称的方法形式化。

我认为,实现这一目标的一种方法是在互联网上找到适用于您所在地区/国家的通用城市表格,例如以任何格式(邮政编码,政府统计数据......),并使用此表格从这个表来自地址行。

对于MySQL

SELECT TRIM(TRIM(TRAILING Cities.Name FROM Address) ), Cities.Name
from All_Students left join Cities 
     on All_Students.Address like CONCAT('% ',Cities.Name)

对于MS SQL Server

SELECT LEFT(Address,LEN(Address)-LEN(Cities.Name)), Cities.Name
from All_Students left join Cities 
     on All_Students.Address like '% '+Cities.Name

要根据评论中的要求在MS SQL中更新,请使用:

UPDATE
    A
SET
    A.address = B.NewAddress,
    A.City = B.City
FROM
    Transformed_All_Student A
    JOIN
    (
      SELECT Student_id, 
             LEFT(Address,LEN(Address)-LEN(Cities.Name)) as NewAddress, 
             Cities.Name as City
      from All_Students left join Cities 
         on All_Students.Address like '% '+Cities.Name

    ) B 
ON A.Student_ID = B.Student_id