如何在使用concat_ws的postgresql视图中将null值作为文本'N / A'返回

时间:2015-06-02 16:20:35

标签: postgresql views

我需要使用concat_ws查询5列(为kml文件创建只有一个描述字段的文本,我需要5列的信息),在连接列之间我想在两列之前添加文本:

SELECT concat_ws(' '::text, col1, col2, col3, 
'text_for_4:', col4, 
'text_for_5:', col5) AS concat_ws,..

这样可以正常工作,但是如果一行有空值,我可以创建一个返回'N / A'文本的查询吗?即如果col4为null,则返回'col1 col2 col3 text_for_4:N / A text_for_5:col5'

2 个答案:

答案 0 :(得分:3)

使用COALESCE

SELECT concat_ws(' '::text, COALESCE ( col1, 'N/A' ), COALESCE ( col2, 'N/A' ),
COALESCE ( col3, 'N/A' ), 
'text_for_4:', COALESCE ( col4, 'N/A' ), 
'text_for_5:', COALESCE ( col5, 'N/A' )) AS concat_ws,..

答案 1 :(得分:0)

使用CASE语句(http://www.postgresql.org/docs/9.3/static/functions-conditional.html):

select 
  case 
    when column is null 
    then 'N/A'
    else column
  end
from table;