如何获得多个列的不同列值作为具有相应列名的数组?

时间:2018-08-14 14:42:40

标签: sql postgresql-9.1

我试图获取多个列的不同值作为数组。我尝试使用功能array_agg

    Color  |  State     |  Item
=================================
    Red    |  New York  |  Balloon
    Pink   |  Virginia  |  Table
    Black  |  Utah      |  Table

我想要一张桌子

    Column_name  | Options
===============================
    Color        | [Red,Pink,Black]
    State        | [New York,Virginia,Utah]
    Item         | [Balloon,Table]

我已经尝试过了:

select (array_agg(distinct "Color"))  from sample_table
union 
select (array_agg(distinct "State")) from sample_table
union 
select (array_agg(distinct "Item")) from sample_table
union 

我被困在如何获取相应的列名中。.

1 个答案:

答案 0 :(得分:1)

您只需要添加您的column_name:

SELECT 'Color' AS column_name, array_agg(distinct "Color") AS options from sample_table
UNION
SELECT 'State' AS column_name, array_agg(distinct "State") AS options from sample_table
UNION
SELECT 'Item' AS column_name, array_agg(distinct "Item") AS options from sample_table

工作Fiddle