2014-07-23 71 views
0

我有一個表的一些基本地址數據:智能COALESCE

table structure

如果街道和郵編/鎮充滿,我希望街和郵政編碼/鎮以逗號分隔。

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

如果路邊沒有用,我想剛纔的郵政編碼和城鎮用空格隔開,如果連郵編缺少我只想名字(如果只是郵編丟失,我'd喜歡有「街道,城鎮」)

我該如何設計查詢,以便它考慮哪些可用以及逗號和空白需要放在哪裏?

+0

使用'CASE WHEN。 END'結構。 –

回答

2

與內置concat_ws()與做最簡單的方法來檢查空字符串:

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

如果任何參數是NULL(除了分隔符),然後concat_ws(),只需跳過該字符串和a相關分隔符。

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 <> ''

0

選擇街頭|| ' '||鎮||', '|| COALESCE(郵編,空,'')從LCI_DW_views.UACI_TRMTRULEINV其中offername LIKE '%644970%'