PostgreSQL:select查询中的字符串连接

时间:2014-08-25 10:46:57

标签: sql postgresql

以下是我的选择查询

select 
     case
      when mobile||', '||phoneoff  <>', ' then mobile||', '||phoneoff 
      when phoneoff='' and mobile<>''  then mobile 
      when phoneoff<>'' and mobile='' then phoneoff 
     else 'NIL' 
     end as "Concat_result",phoneoff,mobile
from gtab12  


结果

      Concat_result|  phoneoff  | mobile
-------------------+------------+----------  
9544070335, 2812111|2812111     |9544070335
                NIL|            |
     , 0479-2436762|0479-2436762|
       9495758057, |            |9495758057

我想要实现的目标是,如果phoneoffmobile都有价值,那么它应该与, Concat_result连接{ 结果中第一个中的<1}} col
如果phoneoffmobile= '',则Concat_result应打印NIL
如果phoneoff<>''mobile='',则Concat_result应仅打印phoneoff(请参阅我的结果中的 3,其中显示phoneoff } ,}和mobile<>''

相同


期待结果

      Concat_result|  phoneoff  | mobile
-------------------+------------+----------  
9544070335, 2812111|2812111     |9544070335
                NIL|            |
      0479-2436762 |0479-2436762|           
       9495758057  |            |9495758057

3 个答案:

答案 0 :(得分:2)

Postgres有concat_ws,这可以提供帮助:

select concat_ws(', ', phoneoff, mobile) as Concat_result, phoneoff, mobile
from gtab12 ;

这并不是你想要的,因为你关心特殊值和'NIL'。所以,让我们把这个逻辑放在:

select (case when phoneoff = '' and mobile = '' then 'NIL'
             else concat_ws(', ',
                            (case when phoneoff <> '' then phoneoff end),
                            (case when mobile <> '' then mobile end)
                           )
        end) as Concat_result, phoneoff, mobile
from gtab12 ;

答案 1 :(得分:2)

简单的单行,使用NULLIF()&amp; COALESCE()(因此也可以处理NULL值,而不仅仅是空字符串):

select coalesce(nullif(concat_ws(', ', nullif(phoneoff, ''), nullif(mobile, '')), ''), 'NIL') "Concat_result", phoneoff, mobile
from gtab12

答案 2 :(得分:1)

select 
 case
    when (mobile<>'' and phoneoff<>'') then mobile||', '||phoneoff 
    when phoneoff='' and mobile<>''  then mobile 
    when phoneoff<>'' and mobile='' then phoneoff 
    else 'NIL' 
 end as "Concat_result",phoneoff,mobile
from gtab12