如何删除、替换postgresql中字段的数据以简化它们



我被困在这一点上,我正试图使用postgresql清理表的行名。该表适用于威尔士和英格兰的地区。

我正在尝试删除字符串"District"、"(B("、"London Boro"以及英语-威尔士双重名称中连字符之前的所有内容,例如(Swansea-Abertawe(我想删除连字符前面的所有内容(我想知道如何在两个方向上都这样做(,然后得到(Abertaw(。我使用了前3个字符串,但使用连字符部分,我找不到解决问题的方法。

我试过使用替换和修剪,但没有得到想要的结果。

这是我上次尝试的代码:

select name,
trim(replace(replace(replace(replace(name, 'District', ''), '(B)', ''), 'London Boro', ''),'% - %', ''), ' - ') 
from district;

这是使用的表格样本

name
Swansea - Abertawe
Barnsley District (B)
Bath and North East Somerset
Bedford (B)
Birmingham District (B)
Blackburn with Darwen (B)
Blackpool (B)
Blaenau Gwent - Blaenau Gwent
Bolton District (B)
Bournemouth (B)
Bracknell Forest (B)
Bradford District (B)
The Vale of Glamorgan - Bro Morgannwg
Aylesbury Vale District
Chiltern District
South Bucks District
Wycombe District
Bury District (B)
Cardiff - Caerdydd
Caerphilly - Caerffili
Calderdale District (B)
Cambridge District (B)
East Cambridgeshire District
City of Westminster London Boro
Croydon London Boro
Ealing London Boro
Enfield London Boro
Castell-nedd Port Talbot - Neath Port Talbot

这就是我想要获得的:

name
Abertawe
Barnsley
Bath and North East Somerset
Bedford
Birmingham
Blackburn with Darwen
Blackpool
Blaenau Gwent
Bolton
Bournemouth
Bracknell Forest
Bradford
Bro Morgannwg
Aylesbury Vale
Chiltern
South Bucks
Wycombe
Bury
Caerdydd
Caerffili
Calderdale
Cambridge
East Cambridgeshire
City of Westminster
Croydon
Ealing
Enfield
Neath Port Talbot

谢谢,

使用Case语句来区分这两个条件,并使用Position函数来检查-是否存在。

试试这个

select
name,
case when position(' - ' in name)>0 then 
trim(replace(replace(replace(substr(name,position(' - ' in name)+3,length(name)), 'District', ''), '(B)', ''), 'London Boro', ''))
else 
trim(replace(replace(replace(name, 'District', ''), '(B)', ''), 'London Boro', ''))
end 
from district

演示

最新更新