首页 > 解决方案 > 如何将多列的列不同值作为具有相应列名的数组获取?

问题描述

我试图将多列的不同值作为数组获取。我试过使用这个功能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 

我被困在如何获得相应的列名..!

标签: sqlpostgresql-9.1

解决方案


你只需要像这样添加你的 column_names :

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

工作小提琴


推荐阅读