Postgresql仅连接非空字符串

时间:2018-01-13 16:42:32

标签: sql postgresql if-statement

想象一下,您在表格中有一些类似于以下内容的数据......

line1               line2               line3       city        zipcode
1 Any Road          NULL                NULL        Big Apple   12345
The White House     Pennsylvania Avenue NULL        Washington  20500
10 Downing Street   NULL                NULL        London      SW1A 2AA

如何返回非空字段的值。以“白宫”为例我想返回除 line3 之外的所有字段的值(因为它具有空值)...

The White House, Pennsylvania Avenue, Washington, 20500

而不是......

The White House, Pennsylvania Avenue, **,** Washington, 20500

我正在尝试将ACE / JET / MS Access查询转换为其Postgresql等效项。在Access中我使用类似于......的IIF

Select
    IIF(line1 <> '', ', ' + line1, '')
    + IIF(line2 <> '', ', ' + line2, '')
    + IIF(line3 <> '', ', ' + line3, '')
    + IIF(city <> '', ', ' + city, '')
    + IIF(zipcode <> '', ', ' + zipcode, '') as CustDetails
From addresses

这将完全满足我的需要。然而,Postgres似乎没有IIF条件。我想我需要使用'CASE WHEN THEN',但我正在努力让我的头围绕着筑巢的东西。例如....

SELECT 
 CASE 
     WHEN line1 <> '' THEN line1  || ', '
     WHEN line2 <> '' THEN line2  || ', '
     WHEN line3 <> '' THEN line3  || ', '
     WHEN line4 <> '' THEN line4
 END AS CustDetails
FROM addresses

只是回来......

custDetails
The White House,

如何嵌套Case语句以仅在结果中显示非空值?

2 个答案:

答案 0 :(得分:2)

使用concat_ws()(concat&#34; with separator&#34;)它将正确处理空字符串和空字符串:

SELECT concat_ws(',', line1, line2, line3, line4, city, zipcode) as cust_details
FROM addresses;

如果任何元素为null或空字符串(''

,则不会添加分隔符

答案 1 :(得分:1)

您正在寻找concat_ws()

concat_ws(',', line1, line2, line3, city, zipcode)