sql - 如何将多列的列不同值作为具有相应列名的数组获取?
问题描述
我试图将多列的不同值作为数组获取。我试过使用这个功能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
我被困在如何获得相应的列名..!
解决方案
你只需要像这样添加你的 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
工作小提琴
推荐阅读
- python - 检测视频中的人脸,裁剪它们并以相同的顺序保存所有帧 - opencv python
- google-apps-script - .getEditors() 返回 'DriveUser,DriveUser'
- java - 打印时缺少报告
- java - 如何将模拟注入具有 1 个带参数的构造函数的类中?
- javascript - 如何使用 Javascript 生成由外部库提供的 Angular 组件?
- python - 如何使用 python 访问 DOORS 内容?
- javascript - 为谷歌饼图保存颜色,甚至切片为 0%
- python - 从数组中获取前 70 个值并将它们放入新维度的最有效方法
- mysql - Laravel 空密码哈希
- android - 可以在插入耳机的情况下正常通话吗?