【问题标题】:Intelligent coalesce智能合并
【发布时间】:2014-07-23 18:54:53
【问题描述】:

我有一个包含一些基本地址数据的表格:

如果 Street 和 Postcode/Town 已填满,我希望 Street 和 Postcode/Town 用逗号分隔。

select Concat(coalesce(Street,''),", ", coalesce(Postcode,'')," ",coalesce(Town,'')) from adresses

如果街道不可用,我只想用空格分隔邮政编码和城镇,如果甚至缺少邮政编码我只想要名称(如果只是缺少邮政编码,我想要“街道,城镇")

如何设计查询,以便它考虑可用的内容以及逗号和空格需要放在哪里?

【问题讨论】:

  • 使用CASE WHEN ... END 构造。

标签: mysql sql coalesce


【解决方案1】:

使用内置 concat_ws() 最简单的方法:

select concat_ws(', ', Street, Postcode, Town)
from adresses;

如果任何参数为NULL(分隔符除外),则concat_ws() 会跳过该字符串和相关的分隔符。

【讨论】:

    【解决方案2】:
    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 <> ''

    【讨论】:

      【解决方案3】:

      select street||','||town||','||coalesce(postcode,null,'') from LCI_DW_views.UACI_TRMTRULEINV where offername like '%644970%'

      【讨论】:

        猜你喜欢
        • 2020-09-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-09-02
        • 2014-06-25
        • 1970-01-01
        • 2015-07-03
        • 2023-01-25
        相关资源
        最近更新 更多