2

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

地址有不同的格式,例如

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
4

1 回答 1

2

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

我认为做到这一点的一种方法是在互联网上为您所在地区/国家/地区找到一个通用城市表,例如以任何格式(邮政编码、政府统计数据......)并使用此表从该表中删除 Cities地址行。

对于 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 服务器

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
于 2012-12-11T12:56:26.910 回答