如何在全国各地的地址中提取省份和城市?

楼主
我是社区第836889位番薯,欢迎点我头像关注我哦~

【数据连接默认mysql】

全国的省市有三种情况:

1.直辖市,没有省份,省的字符串长度为0,市的字符串长度为3;

例如:天津市南开区南开医院

2.XX省,XXX市,省和市的字符串长度都是3;

例如:广东省惠州市博罗县横河镇

3.N省,N市,省和市的字符串长度不固定;

例如:云南省文山壮族苗族自治州文山市新平街道

          内蒙古自治区呼和浩特市新城区

 

思路:

1.先将提取出省份名称

2.计算省份的字符长度

3.计算城市的字符长度

4.做判断,如果这个地址属于直辖市,则截取前3个字符,如果不是,则从省份的最后一个字的位置开始截取字符串,到城市的最后一个字结束,便可以提取出城市名称;

 

步骤:

①全国有8个省的名称字符不等于3,其中5个自治区,黑龙江,4个直辖市,使用case when then else end、instr、substring;

例如:

select

case 

when instr(location,"内蒙古自治区")>0 then '内蒙古自治区'

when instr(location,"黑龙江省")>0 then '黑龙江省'

when instr(location,"广西壮族自治区")>0 then '广西壮族自治区'

when instr(location,"西藏自治区")>0 then '西藏自治区'

when instr(location,"宁夏回族自治区")>0 then '宁夏回族自治区'

when instr(location,"新疆维吾尔自治区")>0 then '新疆维吾尔自治区'

when instr(location,"香港特别行政区")>0 then '香港特别行政区'

when instr(location,"澳门特别行政区")>0 then '澳门特别行政区'

when instr(location,"天津市")>0 then '天津市'

when instr(location,"北京市")>0 then '北京市'

when instr(location,"上海市")>0 then '上海市'

when instr(location,"重庆市")>0 then '重庆市'

else substring(location,1,3)

  end as '送达省份'

from A

 

②计算①中获取到的省份字符长度,使用CHAR_LENGTH;

例如:

select

CHAR_LENGTH(送达省份)

from B

 

③全国的城市名称大部分字符长度为3,少部分字符长度不固定,使用case when then else end、instr、locate;

例如:

select 

 case 

when instr(location,"兴安盟")>0 then locate('兴安盟',location)+2

when instr(location,"锡林郭勒盟")>0 then locate('锡林郭勒盟',location)+4

when instr(location,"阿拉善盟")>0 then locate('阿拉善盟',location)+3

when instr(location,"大兴安岭地区")>0 then locate('大兴安岭地区',location)+5

when instr(location,"阿里地区")>0 then locate('阿里地区',location)+3

when instr(location,"和田地区")>0 then locate('和田地区',location)+3

when instr(location,"喀什地区")>0 then locate('喀什地区',location)+3

when instr(location,"塔城地区")>0 then locate('塔城地区',location)+3

when instr(location,"阿克苏地区")>0 then locate('阿克苏地区',location)+4

when instr(location,"阿勒泰地区")>0 then locate('阿勒泰地区',location)+4

when instr(location,"巴音郭楞蒙古自治州")>0 then locate('巴音郭楞蒙古自治州',location)+8

when instr(location,"克孜勒苏柯尔克孜自治州")>0 then locate('克孜勒苏柯尔克孜自治州',location)+10

when instr(location,"昌吉回族自治州")>0 then locate('昌吉回族自治州',location)+6

when instr(location,"博尔塔拉蒙古自治州")>0 then locate('博尔塔拉蒙古自治州',location)+8

when instr(location,"伊犁哈萨克自治州")>0 then locate('伊犁哈萨克自治州',location)+7

else locate('市',location)

  end as '送达市定位'

from A

 

④因为直辖市没有省份,所以在①获取到的是直辖市的名称,会导致在②求省份字符长度和③求城市长度都是3,所以需要用到case when then else end、instr、substring、CHAR_LENGTH

例如:

select

case

when instr(a.送达地址,"天津市")>0 then '天津市'

when instr(a.送达地址,"北京市")>0 then '北京市'

when instr(a.送达地址,"上海市")>0 then '上海市'

when instr(a.送达地址,"重庆市")>0 then '重庆市'

else substring(

                           a.送达地址,CHAR_LENGTH(a.送达省份)+1,a.送达市定位-CHAR_LENGTH(a.送达省份)

                           )

end '送达市'

from B

 

分享扩散:

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

0回帖数 1关注人数 3695浏览人数
最后回复于:2022-3-24 17:45

返回顶部 返回列表