postgresql从查询的多列返回第一个正值

时间:2015-03-15 07:50:05

标签: postgresql

我在POstgreSQL数据库中有一个表,其中有多列,其中只有一列会输入一个值。

    SELECT "Garden_GUID", "Municipality_Amajuba", "Municipality_Ilembe", "Municipality_Sisonke" from forms_garden
WHERE "Garden_GUID" = 'testguid';
 Garden_GUID | Municipality_Amajuba | Municipality_Ilembe | Municipality_Sisonke 
-------------+----------------------+---------------------+----------------------
 testguid    | Dannhauser           |                     | 
(1 row)

我希望创建一个视图,将这些列中的条目合并为一个列。

我试过了:

CREATE VIEW municipality (GUID,funder,municipality)
AS SELECT "Garden_GUID"GUID,"Funder"funder,"Municipality_Amajuba","Municipality_Ilembe","Municipality_Sisonke"municipality
FROM forms_garden;

但它返回错误:

错误:专栏"自治市"指定不止一次

有没有办法逐行查询各种municipality_ *列,只返回第一个正条目?

非常感谢提前。

1 个答案:

答案 0 :(得分:1)

我认为coalesce()正是您所寻找的:

with forms_garden as (
    select 'guid1' guid, 'Dannhauser' amajuba, null ilembe, null sisonke
    union all select 'guid2', null, 'muni2', null
    union all select 'guid3', null, null, 'muni3'
) select guid, coalesce(amajuba,ilembe,sisonke) municipality from forms_garden;