如何将多列的列不同值作为具有相应列名的数组获取?
How to get column distinct values of multiple columns as array with corresponding column name?
我正在尝试将多列的不同值作为数组获取。我试过使用函数 array_agg
Color | State | Item
=================================
Red | New York | Balloon
Pink | Virginia | Table
Black | Utah | Table
我想要一个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
我卡在如何获取相应的列名了..!
您只需像这样添加 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
工作Fiddle
我正在尝试将多列的不同值作为数组获取。我试过使用函数 array_agg
Color | State | Item
=================================
Red | New York | Balloon
Pink | Virginia | Table
Black | Utah | Table
我想要一个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
我卡在如何获取相应的列名了..!
您只需像这样添加 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
工作Fiddle