如何在使用 concat_ws 的 postgresql 视图中将 return 空值作为文本 'N/A'
How to return null value as text 'N/A' in a postgresql view that uses concat_ws
我有 5 列需要使用 concat_ws 查询(为只有一个描述字段的 kml 文件制作文本,我需要 5 列的信息),并且在我想要的串联列之间在两列前添加文本:
SELECT concat_ws(' '::text, col1, col2, col3,
'text_for_4:', col4,
'text_for_5:', col5) AS concat_ws,..
这很好用,但是我可以创建一个查询,如果某行有空值,该查询将 return 'N/A' 的文本吗? IE。如果 col4 为空,则 return 将是 'col1 col2 col3 text_for_4: N/A text_for_5: col5'
使用 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;
使用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,..
我有 5 列需要使用 concat_ws 查询(为只有一个描述字段的 kml 文件制作文本,我需要 5 列的信息),并且在我想要的串联列之间在两列前添加文本:
SELECT concat_ws(' '::text, col1, col2, col3,
'text_for_4:', col4,
'text_for_5:', col5) AS concat_ws,..
这很好用,但是我可以创建一个查询,如果某行有空值,该查询将 return 'N/A' 的文本吗? IE。如果 col4 为空,则 return 将是 'col1 col2 col3 text_for_4: N/A text_for_5: col5'
使用 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;
使用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,..