以下是我的选择查询
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
我想要实现的目标是,如果phoneoff
和mobile
都有价值,那么它应该与,
Concat_result
连接{ 结果中第一个行中的<1}} col
如果phoneoff
和mobile
为= ''
,则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
答案 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