如果一个或多个列为空,请在一个字段中选择多个列

时间:2011-04-13 15:13:39

标签: sql postgresql if-statement conditional concatenation

运行PostgreSQL 7.4(是的,我们正在升级......)

查询:

SELECT (
     "Address" ||' '|| 
     "Address 2" ||' '|| 
     "City" ||' '|| 
     "State" ||' '|| 
     "Zip"
) AS full_address
FROM database
WHERE condition

除非一个或多个字段为空/空白,否则全部按预期工作。

因此,如果地址2为空/空,则不返回任何内容。

问题:

如何使用IF(或CASE)条件检查地址2是否有值,如果是,则添加,否则跳过

2 个答案:

答案 0 :(得分:3)

使用coalesce:

select coalesce (someColumn, 'default-if-column-blank')

答案 1 :(得分:2)

SELECT (
     "Address" ||' '|| 
     COALESCE("Address 2" ||' ', '') ||
     "City" ||' '|| 
     "State" ||' '|| 
     "Zip"
) AS full_address
FROM database
WHERE condition

http://www.postgresql.org/docs/7.4/static/functions-conditional.html#AEN11443