如何获取 Postgres 中单个表中所有列的不同值?

Pat*_*ivo 1 sql postgresql json jsonb

理想情况下,我想运行一个查询,返回一个表,其中每一行都是指定表的列名,并且jsonb表中与该列对应的所有不同值的数组。

棘手的部分似乎是动态执行的,我可以只指定表而不是每个单独的列。

我可以从 中检索相关表的所有列名information_schema.columns,但是有没有一种简单的方法可以将其与查询结合起来以检索每列的所有不同值?

kli*_*lin 5

create table example(id int primary key, str text, val numeric);
insert into example values
(1, 'a', 1),
(2, 'a', 2),
(3, 'b', 2);

select key, array_agg(distinct value)
from example, jsonb_each_text(to_jsonb(example))
group by key;

 key | array_agg 
-----+-----------
 id  | {1,2,3}
 str | {a,b}
 val | {1,2}
(3 rows)    
Run Code Online (Sandbox Code Playgroud)

或者

select key, json_agg(distinct value)
from example, jsonb_each(to_jsonb(example))
group by key;

 key |  json_agg  
-----+------------
 id  | [1, 2, 3]
 str | ["a", "b"]
 val | [1, 2]
(3 rows)    
Run Code Online (Sandbox Code Playgroud)