我有一张包含一些基本地址数据的表格:
如果填写街道和邮编/城镇,我希望以逗号分隔街道和邮编/城镇。
select Concat(coalesce(Street,''),", ", coalesce(Postcode,'')," ",coalesce(Town,'')) from adresses
如果街道不可用,我想只用邮政编码和城镇分隔一个空白,即使邮政编码丢失,我只想要名称(如果只是邮政编码丢失,我想要“街,镇“)
如何设计查询以便考虑可用内容以及需要放置逗号和空白的位置?
答案 0 :(得分:2)
使用内置concat_ws()
:
select concat_ws(', ', Street, Postcode, Town)
from adresses;
如果任何参数是NULL
(除了分隔符),那么concat_ws()
只是跳过该字符串和相关的分隔符。
答案 1 :(得分:1)
select
(case when
street is not null
and postcode is not null
and town is not null
then concat(street,', ',postcode,', ',town)
when
street is null
and postcode is not null
and town is not null
then concat(postcode,' ',town)
when
street is null
and postcode is null
and town is not null
then town
else 'N/A'
end) myAddress
from address
您可能需要根据您的数据检查空字符串,例如
when street is not null and street <> ''
答案 2 :(得分:0)
从LCI_DW_views选择街道||&#39;,&#39; ||城镇||&#39;,&#39; ||合并(邮编,空,&#39;&#39;)。 UACI_TRMTRULEINV,其名称如&#39;%644970%&#39;